package com.cloud.system.api.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cloud.system.api.bean.*;
import com.cloud.system.api.entity.*;
import com.cloud.system.api.enums.YesNoEnum;
import com.cloud.system.api.mapper.*;
import com.cloud.system.api.service.SysDictService;
import com.cloud.system.api.service.SystemCacheService;
import com.cloud.system.api.service.UnitInfoService;
import com.cloud.system.api.web.SystemInterfaceController;
import com.cloud.system.common.consts.SystemConst;
import com.cloud.system.common.result.QkTreeNode;
import com.cloud.system.common.result.SelectItem;
import com.cloud.system.common.utils.*;
import com.cloud.system.interfaces.FeignClientCheck;
import com.cloud.system.interfaces.FeignClientForce;
import com.cloud.system.interfaces.FeignClientPunish;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class UnitInfoServiceImpl implements UnitInfoService {

    private static final Logger logger = LoggerFactory.getLogger(UnitInfoServiceImpl.class);

    @Autowired
    private UnitInfoMapper unitInfoMapper;

    @Autowired
    private UnitPowerMapper unitPowerMapper;

    @Autowired
    private UnitPermitMapper unitPermitMapper;

    @Autowired
    private UnitInspectMapper unitInspectMapper;

    @Autowired
    private UnitSuperviseMapper unitSuperviseMapper;

    @Autowired
    private UnitDomainMapper unitDomainMapper;

    @Autowired
    private HumanInfoMapper humanInfoMapper;

    @Autowired
    private RoleInfoMapper roleInfoMapper;

    @Autowired
    private HumanRoleMapper humanRoleMapper;

    @Autowired
    private DicRegionMapper dicRegionMapper;

    @Autowired
    private SystemCacheService systemCacheService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private TemporaryPowerMapper temporaryPowerMapper;

    @Autowired
    private PowerBasisMapper powerBasisMapper;

    @Autowired
    private FeignClientPunish feignClientPunish;

    @Autowired
    private FeignClientForce feignClientForce;

    @Autowired
    private FeignClientCheck feignClientCheck;

    @Autowired
    private SystemInterfaceController systemInterfaceController;

    @Override
    public List<QkTreeNode> listUnitTree(long unitId, boolean isRoot, String isSupervise, boolean isScreen) {
        // 0918修改 组织机构树不再使用细分领域作为过滤条件，每个登录人就只能看到自己的所属单位及下级单位
        List<QkTreeNode> nodes = new ArrayList<QkTreeNode>();

        List<Integer> unitTypeIDs = new ArrayList<>();
        if (StringUtils.isNotEmpty(isSupervise) && "true".equals(isSupervise)) {
            unitTypeIDs.add(5);
        } else {
            unitTypeIDs.add(2);
            unitTypeIDs.add(5);
            unitTypeIDs.add(4);
            unitTypeIDs.add(6);
        }
        // 判断登录人的单位是否为行政区划，如果是行政区划的则不需要进行领域过滤，否则进行领域过滤
        UnitInfo SessionUnit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId());
        boolean isArea = "0".equals(SessionUnit.getUnitTypeId());

        QkTreeNode rootNode = null;
        UnitInfo rootUnit = null;
        if (isRoot) {
            if (unitId != 0) {
                rootUnit = unitInfoMapper.selectByPrimaryKey(unitId);
            } else {
                rootUnit = SessionUnit;
            }
            // 根节点修改为所在部门的行政区划
            if (isArea) {
                rootUnit = getRegionInfo(rootUnit.getRegionCode(), isScreen);
            }
            rootNode = new QkTreeNode(rootUnit.getUnitId(), rootUnit.getUnitName());
            rootNode.setRootFlag(true);
            rootNode.setSelectable(true);
            if ("0".equals(rootUnit.getUnitTypeId())) {
                rootNode.setIcon("area");
            } else if ("4".equals(rootUnit.getUnitTypeId())) {
                rootNode.setIcon("entrust");
            } else if ("6".equals(rootUnit.getUnitTypeId())) {
                rootNode.setIcon("supervise");
            } else if ("7".equals(rootUnit.getUnitTypeId())) {
                rootNode.setIcon("common");
            } else {
                rootNode.setIcon("unit");
            }
            rootNode.getData().put("type", "U");
            rootNode.getData().put("code", rootUnit.getUnitCode());
            rootNode.setExpanded(true);
        }
        if (null != rootNode) {
            nodes.add(rootNode);
        }

        // 加载下级机构
        List<QkTreeNode> childrens = new ArrayList<QkTreeNode>();
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(isSupervise)) {
            if ("true".equals(isSupervise)) {
                List<Integer> unitTypeIds = new ArrayList<Integer>();
                // 展示行政区划和监督部门
                unitTypeIds.add(0);
                unitTypeIds.add(5);
                criteria.andIn("unitTypeId", unitTypeIds);
            } else if ("false".equals(isSupervise)) {
                criteria.andNotEqualTo("isLawOrgans", "0");
//                criteria.andNotEqualTo("unitTypeId", "0");
            }
        }
        criteria.andNotEqualTo("deleteFlag", 1);
        criteria.andEqualTo("seniorId", null != rootUnit ? rootUnit.getUnitId() : unitId);
        example.orderBy("displayOrder").asc();
        List<UnitInfo> units = unitInfoMapper.selectByExample(example);

        // 判断下级机构是否为叶子节点
        if (null != units && units.size() > 0) {
            List<Long> uids = new ArrayList<>();
            uids.add(SessionUnit.getUnitId());
            List<Long> unitChildrenCounts = unitInfoMapper.selectUnitChildrenCount(uids, unitTypeIDs);

            for (UnitInfo u : units) {
                QkTreeNode node = new QkTreeNode(u.getUnitId(), u.getUnitName());
                if ("0".equals(u.getUnitTypeId())) {
                    node.setIcon("area");
                } else if ("4".equals(u.getUnitTypeId())) {
                    node.setIcon("entrust");
                } else if ("6".equals(u.getUnitTypeId())) {
                    node.setIcon("supervise");
                } else if ("7".equals(u.getUnitTypeId())) {
                    node.setIcon("common");
                } else {
                    node.setIcon("unit");
                }
                if ("5".equals(u.getUnitTypeId()) && u.getIsLawOrgans() == 1) {
                    u.setUnitTypeId("2");
                }
                node.setSelectable(true);
                node.getData().put("type", "U");
                node.getData().put("code", u.getUnitCode());
                node.setLeaf(true);
                //有子节点或者是登录人员所在部门的上层节点时设置为非叶子节点
                if (null != unitChildrenCounts && unitChildrenCounts.contains(u.getUnitId())) {
                    node.setLeaf(false);
                } else if ((SessionUnit.getUnitCode().indexOf(u.getUnitCode()) > -1 && !SessionUnit.getUnitId().equals(u.getUnitId())) || !checkLeafUnit(u, SessionUnit, unitTypeIDs)) {
                    node.setLeaf(false);
                } else if ("0".equals(u.getUnitTypeId()) && containDirectUnit(u.getUnitId()) > 0) {
                    node.setLeaf(false);
                }
                if (isArea) {
                    childrens.add(node);
                } else {
                    if (!"0".equals(u.getUnitTypeId())) {
                        // 0909 修改 展示领域交集和父级单位下所有部门
                        if (SessionUnit.getUnitId().equals(u.getUnitId()) || u.getUnitCode().indexOf(SessionUnit.getUnitId().toString()) > -1) {
                            childrens.add(node);
                        }
                    } else {
                        childrens.add(node);
                    }
                }

            }
        }
        if (nodes.size() != 1) {
            return childrens;
        } else {
            nodes.get(0).setChildren(childrens);
        }
        return nodes;
    }

    private UnitInfo getRegionInfo(String regionCode, boolean isScreen) {
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("regionCode", regionCode);
        criteria.andEqualTo("unitTypeId", 0);
        UnitInfo unitInfo = unitInfoMapper.selectByExample(example).get(0);

        //直属部门 ，就再找一级
        if (unitInfo.getUnitName().indexOf("直属") > -1 && !isScreen) {
            example = new Example(UnitInfo.class);
            criteria = example.createCriteria();
            criteria.andEqualTo("unitId", unitInfo.getSeniorId());
            criteria.andEqualTo("unitTypeId", 0);
            unitInfo = unitInfoMapper.selectByExample(example).get(0);
        }
        return unitInfo;
    }

    private boolean checkSeniorUnit(Long unitID) {
        boolean isArea = false;
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("unitId", unitID);
        List<UnitInfo> unitInfos = unitInfoMapper.selectByExample(example);
        if (unitInfos != null && unitInfos.size() > 0) {
            if ("0".equals(unitInfos.get(0).getUnitTypeId())) {
                isArea = true;
            } else {
                isArea = false;
            }
        }

        return isArea;
    }


    private boolean checkLeafUnit(UnitInfo node, UnitInfo sessionUnit, List<Integer> unitTypeIds) {
        boolean isLeaf = true;
        if (node.getUnitCode().contains(sessionUnit.getUnitId().toString())) {
            List<Long> list = new ArrayList<>();
            list.add(node.getUnitId());
            List<Long> longs = unitInfoMapper.selectUnitChildrenCount(list, unitTypeIds);
            if (longs.contains(node.getUnitId())) {
                isLeaf = false;
            }
        }
        return isLeaf;
    }


    @Override
    public UnitInfo load(long unitId) {
        UnitInfo info = unitInfoMapper.selectByPrimaryKey(unitId);
        if (null != info.getSeniorId() && info.getSeniorId().longValue() > 0) {
            UnitInfo parent = unitInfoMapper.selectByPrimaryKey(info.getSeniorId());
            info.setSeniorName(parent.getUnitName());
            // 判断父级机构是否为行政区划
            if (!parent.getUnitTypeId().equals("0")) {
                List<UnitDomain> parentList = getDomainLists(parent.getUnitId());
                List<String> doMainIDs = new ArrayList<>();
//                List<String> subDoMainIDs = new ArrayList<>();
                if (parentList.size() > 0) {
                    for (UnitDomain domain : parentList) {
                        if (!doMainIDs.contains(domain.getDomainTypeId())) {
                            doMainIDs.add(domain.getDomainTypeId());
                        }
//                        subDoMainIDs.add(domain.getSubDomainTypeId());
                    }
                }
                if (doMainIDs.size() > 0) {
//                    String[] parentSubDomains = new String[subDoMainIDs.size()];
                    String[] parentDomains = new String[doMainIDs.size()];
                    for (int i = 0, size = doMainIDs.size(); i < size; i++) {
                        parentDomains[i] = doMainIDs.get(i).toString();
                    }
//                    for (int i = 0, size = subDoMainIDs.size(); i < size; i++) {
//                        parentSubDomains[i] = subDoMainIDs.get(i).toString();
//                    }
                    info.setParentUnitDomains(parentDomains);
//                    info.setParentUnitSubDomains(parentSubDomains);
                }
            }
        }
        // 所属领域回显
        List<UnitDomain> list = getDomainLists(unitId);
        if (list.size() > 0) {
            List<String> doMainIDs = new ArrayList<>();
//            List<String> subDoMainIDs = new ArrayList<>();
            List<String> doMainValues = new ArrayList<>();
//            List<String> subDoMainValues = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                // 字段中的值为（01，02，03......）
                if (list.get(i).getDomainTypeId().length() == 1) {
                    if (!doMainIDs.contains("0" + list.get(i).getDomainTypeId())) {
                        doMainIDs.add("0" + list.get(i).getDomainTypeId());
                    }
//                    subDoMainIDs.add("0" + list.get(i).getSubDomainTypeId());
                } else {
                    if (!doMainIDs.contains(list.get(i).getDomainTypeId())) {
                        doMainIDs.add(list.get(i).getDomainTypeId());
                    }
//                    subDoMainIDs.add(list.get(i).getSubDomainTypeId());
                }

                doMainValues.add(list.get(i).getDomainTypeName());
//                subDoMainValues.add(list.get(i).getSubDomainTypeName());

            }

            String[] array = new String[doMainIDs.size()];
            for (int i = 0, size = doMainIDs.size(); i < size; i++) {
                array[i] = doMainIDs.get(i).toString();
            }

            info.setUnitDomains(array);
//            array = new String[subDoMainIDs.size()];
//            for (int i = 0, size = subDoMainIDs.size(); i < size; i++) {
//                array[i] = subDoMainIDs.get(i).toString();
//            }
//            info.setUnitSubDomains(array);
            info.setUnitDomainsValue(StringUtils.join(doMainValues, ","));
//            info.setUnitSubDomainsValue(StringUtils.join(subDoMainValues, ","));
        }

        // 所属区域回显
        info.setRegionName(getRegionInfo(info.getRegionCode(), false).getUnitName());
        //主体类别
        List<SelectItem> selectItems = systemCacheService.loadSelectItem(SystemConst.UNIT_TYPE);
        selectItems.forEach(v -> {
            if (v.getValue().equals(info.getUnitTypeId())) {
                info.setUnitTypeName(v.getLabel());
            }
        });
        return info;
    }

    private List<String> getDomainStrings(long unitId) {
        Example example = new Example(UnitDomain.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("unitId", unitId);
        List<UnitDomain> unitDomains = unitDomainMapper.selectByExample(example);
        List<String> list = new ArrayList<>();
        for (UnitDomain domain : unitDomains) {
            list.add(domain.getSubDomainTypeId());
        }
        return list;
    }

    private List<UnitDomain> getDomainLists(long unitId) {
        Example example = new Example(UnitDomain.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("unitId", unitId);
        List<UnitDomain> unitDomains = unitDomainMapper.selectByExample(example);
        return unitDomains;
    }

    private Map<Long, List<String>> getAllSubDomains(long unitId) {

        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("deleteFlag", 1);
        criteria.andEqualTo("seniorId", unitId);
        example.orderBy("displayOrder").asc();
        List<UnitInfo> units = unitInfoMapper.selectByExample(example);

        List<Long> uids = new ArrayList<Long>();
        for (UnitInfo unit : units) {
            uids.add(unit.getUnitId());
        }
        Map<Long, List<String>> allSubDomainMap = new HashedMap();
        if (uids != null && uids.size() > 0) {
            example = new Example(UnitDomain.class);
            criteria = example.createCriteria();
            criteria.andIn("unitId", uids);
            List<UnitDomain> unitDomains = unitDomainMapper.selectByExample(example);

            List<String> list = new ArrayList<>();
            for (Long id : uids) {
                list = new ArrayList<>();
                for (UnitDomain domain : unitDomains) {
                    if (id.equals(domain.getUnitId())) {
                        list.add(domain.getSubDomainTypeId());
                    }
                }
                allSubDomainMap.put(id, list);
            }
        }


        return allSubDomainMap;
    }

    @Override
    public long delete(long unitId) {
        // 逻辑删除机构
        UnitInfo info = unitInfoMapper.selectByPrimaryKey(unitId);
        UnitInfo u = new UnitInfo();
        u.setDeleteFlag(1);
        u.setSendStatus("D");
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("unitCode", info.getUnitCode() + "%");
        unitInfoMapper.updateByExampleSelective(u, example);
        // 逻辑删除人员
        Example humanExample = new Example(HumanInfo.class);
        Example.Criteria humanCriteria = humanExample.createCriteria();
        humanCriteria.andLike("unitCode", info.getUnitCode() + "%");
        HumanInfo human = new HumanInfo();
        human.setDeleteFlag(1);
        humanInfoMapper.updateByExampleSelective(human, humanExample);
        // 逻辑删除岗位
        Example roleExample = new Example(RoleInfo.class);
        Example.Criteria roleCriteria = roleExample.createCriteria();
        roleCriteria.andLike("unitCode", info.getUnitCode() + "%");
        RoleInfo role = new RoleInfo();
        role.setDeleteFlag(1);
        roleInfoMapper.updateByExampleSelective(role, roleExample);
        // 管理员角色删除
        humanRoleMapper.deleteHuman(unitId);
        // 删除机构管理员
        humanInfoMapper.deleteUnitAdminByUnitId(unitId);
        return unitId;
    }

    @Override
    public Map<String,UnitInfo> saveUpdate(UnitInfo info) {
        Map<String,UnitInfo> map = new HashMap<>();
        System.out.println(JSONArray.toJSON(info));
        Long unitId = info.getUnitId();
        info.setDeleteFlag(YesNoEnum.NO.getCode());
        info.setIsLawOrgans(1);
        if (null != unitId && unitId > 0) {
            // 行政区域编码是否重复
            if (info.getUnitTypeId().equals("0")){
                int num = unitInfoMapper.selectRegionCodeByCode(info.getRegionCode(), unitId);
                if (num > 0) {
                    map.put("0", info);
                    return map;
                }
            }
            UnitInfo src = unitInfoMapper.selectByPrimaryKey(info.getUnitId());
            //修改部门信息后，重置信息核实标志位
            if (src.getCreateTime() != null) {
                info.setCreateTime(src.getCreateTime());
            }
            if (src.getCreateHumanId() != null && src.getCreateHumanId() > 0) {
                info.setCreateHumanId(src.getCreateHumanId());
            }
            if (src.getCreateHuman() != null && src.getCreateHuman() != "") {
                info.setCreateHuman(src.getCreateHuman());
            }
            info.setUpdateTime(new Date());
            info.setSendStatus("U");
            info.setSendFlag(0);
            info.setIsConfirm(0);
            info.setUpdateHumanName(SessionHelper.get().getHumanName());
            info.setUpdateHumanId(SessionHelper.get().getHumanId());
            unitInfoMapper.updateByPrimaryKeySelective(info);
            if (!src.getUnitName().equals(info.getUnitName())) {
                // 部门名称变更
                jdbcTemplate.update("update human_info set unit_name = ? where unit_id = ?", info.getUnitName(),
                        info.getUnitId());
                // 管理员名称变更
                String name = info.getUnitName() + "管理员";
                int userNameCounts = humanInfoMapper.countByUserNameAndHumanId(info.getUnitName());
                if (userNameCounts > 0) {
                    jdbcTemplate.update(
                            "update human_info set user_name = concat(unit_name, '管理员', human_id), human_name = concat(unit_name, '管理员') where unit_id = ? and human_type = '00' and human_id > 0",
                            info.getUnitId());
                } else {
                    jdbcTemplate.update(
                            "update human_info set user_name = ?, human_name = ? where unit_id = ? and human_type = '00' and human_id > 0",
                            name, name, info.getUnitId());
                }
            }
            systemCacheService.evitUnitDomainsCache(unitId);
        } else {
            UnitInfo parent = unitInfoMapper.selectByPrimaryKey(info.getSeniorId());
            // 机构名称是否相同。
            int flag = unitInfoMapper.selectByUnitName(info.getUnitName(), parent.getUnitId() );
            if (flag > 0) {
                map.put("1",info);
                return map;
            } else {
                if (info.getUnitTypeId().equals("0")){
                    int num = unitInfoMapper.selectRegionCodeByCode(info.getRegionCode(), new Long(0));
                    if (num > 0) {
                        map.put("0", info);
                        return map;
                    }
                }
                info.setSendFlag(0);
                info.setSendStatus("I");
                // 新增机构
                unitInfoMapper.insert(info);
                info.setCreateHuman(SessionHelper.get().getHumanName());
                info.setCreateHumanId(SessionHelper.get().getHumanId());
                info.setCreateTime(new Date());
                unitId=info.getUnitId();
                info.setDisplayOrder(unitId);
                if (null != parent) {
                    info.setSeniorName(parent.getSeniorName());
                    info.setUnitCode(parent.getUnitCode() + unitId + "/");
//                info.setRegionCode(parent.getRegionCode());
                }
                if (!info.getUnitTypeId().equals("2") && !info.getUnitTypeId().equals("0")){
                    info.setSubjectName(parent.getSubjectName());
                    info.setSubjectId(parent.getSubjectId());
                }else {
                    info.setSubjectId(info.getUnitId());
                    info.setSubjectName(info.getUnitName());
                }
//                unitInfoMapper.insert(info);
                unitInfoMapper.updateByPrimaryKey(info);

                // 如果上级机构为行政区划，为机构创建管理员

                HumanInfo humanInfo = new HumanInfo();
                humanInfo.setUnitId(unitId);
                humanInfo.setUnitName(info.getUnitName());
                humanInfo.setUnitCode(info.getUnitCode());
                humanInfo.setSendStatus("I");
                humanInfo.setSendFlag(0);
                humanInfoMapper.insert(humanInfo);
                long humanId= humanInfo.getHumanId();
                humanInfo.setDeleteFlag(0);
                humanInfo.setLoginFlag(1);
                humanInfo.setHumanType("00");// 管理员默认人员类型
                humanInfo.setDisplayOrder((int)humanId);
                String name = info.getUnitName() + "管理员";
                humanInfo.setHumanName(name);
                int userNameCounts = humanInfoMapper.countByUserNameAndHumanId(name);
                if (userNameCounts > 0) {
                    humanInfo.setUserName(name + humanId);
                } else {
                    humanInfo.setUserName(name);
                }
                String defaultHumanPassword = systemCacheService.loadSysConfigItem(
                        SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD_CONFIG);
                if (StringUtils.isEmpty(defaultHumanPassword)) {
                    defaultHumanPassword = SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD;
                }
                humanInfo.setHumanPassword(
                        DigestUtils.md5Hex(defaultHumanPassword.concat(String.valueOf(humanId))).toUpperCase());

                humanInfoMapper.updateByPrimaryKey(humanInfo);


                // 添加管理员用户对应的岗位
                HumanRole hr = new HumanRole();
                hr.setHumanId(humanId);
                // 获取机构类型对应的岗位信息
                String defaultAdminRoleId = systemCacheService.loadSysConfigItem(
                        SystemConst.DEFAULT_ADMIN_ROLE_ID_PRIFIX + info.getUnitTypeId());
                if (StringUtils.isEmpty(defaultAdminRoleId)) {
                    defaultAdminRoleId = SystemConst.DEFAULT_ADMIN_ROLE_ID;
                }
                if (!StringUtils.isEmpty(defaultAdminRoleId)) {
                    hr.setRoleId(Long.valueOf(defaultAdminRoleId));
                    humanRoleMapper.insert(hr);

                }
            }
        }
        @SuppressWarnings("unchecked")
        Map<String, String> domainCacheMap = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.UNIT_DOMAIN));
        // 删除已选择的领域信息
        Example example = new Example(UnitDomain.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("unitId", unitId);
        unitDomainMapper.deleteByExample(example);
        if (null != info.getUnitDomains() && info.getUnitDomains().length > 0) {
            UnitDomain domain = null;
            for (String unitDomainId : info.getUnitDomains()) {
                domain = new UnitDomain();
                domain.setUnitId(unitId);
                domain.setDomainTypeId(unitDomainId);
                domain.setDomainTypeName(domainCacheMap.get(unitDomainId));
                unitDomainMapper.insert(domain);
            }
        }
//        if (null != info.getUnitSubDomains() && info.getUnitSubDomains().length > 0) {
//            UnitDomain domain = null;
//            for (String unitSubDomainId : info.getUnitSubDomains()) {
//                domain = new UnitDomain();
//                domain.setUnitId(unitId);
//                domain.setDomainTypeId(unitSubDomainId.substring(0, 2));
//                domain.setDomainTypeName(domainCacheMap.get(unitSubDomainId.substring(0, 2)));
//                domain.setSubDomainTypeId(unitSubDomainId);
//                domain.setSubDomainTypeName(domainCacheMap.get(unitSubDomainId));
//                unitDomainMapper.insert(domain);
//            }
//        }
        map.put("2", info);
        return map;
    }

    @Override
    public List<UnitInfo> search(String name) {
        UnitInfo unitInfo = new UnitInfo();
        String unitCode = SessionHelper.get().getUnitCode();
        if (SessionHelper.get().getUnitName().equals("直属部门")) {
            unitCode = unitInfoMapper.selectParentUnitCodeByUnitId(SessionHelper.get().getUnitId());
        }
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        criteria.andLike("unitName", "%" + name + "%");
        criteria.andLike("unitCode", unitCode + "%");
        Page<UnitInfo> unitPage = PageHelper.startPage(1, 20).doSelectPage(() -> {
            unitInfoMapper.selectByExample(example);
        });
        return unitPage.getResult();

    }

    @Override
    public List<SelectItem> loadSeniorSubject(UnitInfo unit) {
        String[] unitIds = unit.getUnitCode().split("/");
        return unitInfoMapper.listSeniorSubject(unitIds);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, List<UnitImportBean>> analyseImportFile(List<UnitImportBean> units) {
        List<UnitImportBean> success = new ArrayList<UnitImportBean>();
        List<UnitImportBean> error = new ArrayList<UnitImportBean>();

        Map<String, String> unitNature = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.UNIT_NATURE_TYPE));
        Map<String, String> unitLevel = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.UNIT_LEVEL));
        Map<String, String> manubriumLevel = MapUtils
                .invertMap(systemCacheService.listDictItemMap(SystemConst.UNIT_MANUBRIUM_LEVEL));
        for (UnitImportBean unit : units) {
            if (StringUtils.isEmpty(unit.getUnitName())) {
                unit.setError(true);
                unit.getErrorMsg().add("机关全称不能为空");
            }
            // 机关性质
            if (!StringUtils.isEmpty(unit.getUnitNatureName())) {
                String unitNatureId = unitNature.get(unit.getUnitNatureName());
                if (StringUtils.isEmpty(unitNatureId)) {
                    unit.setError(true);
                    unit.getErrorMsg().add("机关性质错误");
                }
                unit.setUnitNatureId(unitNatureId);
            }
            // 机关层级
            if (!StringUtils.isEmpty(unit.getUnitLevelName())) {
                String unitLevelId = unitLevel.get(unit.getUnitLevelName());
                if (StringUtils.isEmpty(unitLevelId)) {
                    unit.setError(true);
                    unit.getErrorMsg().add("机关层级填写错误");
                }
                unit.setUnitLevel(unitLevelId);
            }
            // 垂管层级
            if (!StringUtils.isEmpty(unit.getManubriumLevelName())) {
                String manubriumLevelId = manubriumLevel.get(unit.getManubriumLevelName());
                if (StringUtils.isEmpty(manubriumLevelId)) {
                    unit.setError(true);
                    unit.getErrorMsg().add("机关垂管层级填写错误");
                }
                unit.setManubriumLevel(manubriumLevelId);
            }
            if (!StringUtils.isEmpty(unit.getManubriumLevelName()) || !StringUtils.isEmpty(unit.getManubriumName())) {
                unit.setManubriumFlag(1);
            } else {
                unit.setManubriumFlag(0);
            }
            if (unit.isError()) {
                error.add(unit);
            } else {
                success.add(unit);
            }
        }
        Map<String, List<UnitImportBean>> result = new HashMap<String, List<UnitImportBean>>();
        result.put("success", success);
        result.put("error", error);
        return result;
    }

    @Override
    public Map<String, List<PowerImportBean>> powerImportFile(List<PowerImportBean> unitPowers) {
        List<PowerImportBean> success = new ArrayList<PowerImportBean>();
//        Calendar calendar = new GregorianCalendar(1900, 0, -1);
//        Date d = calendar.getTime();
//        Calendar date = Calendar.getInstance();
//        int year = Integer.parseInt(String.valueOf(date.get(Calendar.YEAR)));
        for (PowerImportBean unitPower : unitPowers) {
//            if (!StringUtils.isEmpty(unitPower.getEffectiveDates())) {
//                if (!(unitPower.getEffectiveDates().equals("") || unitPower.getEffectiveDates() == null)) {
//                    unitPower.setEffectiveDate(DateUtils.addDays(d, Integer.valueOf(unitPower.getEffectiveDates())));
//                }
//            }
//            if (!StringUtils.isEmpty(unitPower.getExpiredDates())) {
//                if (!(unitPower.getExpiredDates().equals("") || unitPower.getExpiredDates() == null)) {
//                    unitPower.setExpiredDate(DateUtils.addDays(d, Integer.valueOf(unitPower.getExpiredDates())));
//                }
//            }
            success.add(unitPower);
        }
        Map<String, List<PowerImportBean>> result = new HashMap<String, List<PowerImportBean>>();
        result.put("success", success);
        return result;
    }

    @Override
    public List<UnitInfo> loadChildren(Long unitId) {
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("seniorId", unitId);
        criteria.andEqualTo("deleteFlag", 0);
        example.orderBy("displayOrder");
        return unitInfoMapper.selectByExample(example);
    }

    @Override
    public int reorderUnit(final List<UnitInfo> unitInfo) {
        jdbcTemplate.batchUpdate("update unit_info set display_order = ? where unit_id = ?",
                new BatchPreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                        UnitInfo info = unitInfo.get(i);
                        ps.setLong(1, info.getDisplayOrder());
                        ps.setLong(2, info.getUnitId());
                    }

                    @Override
                    public int getBatchSize() {
                        return unitInfo.size();
                    }
                });
        return unitInfo.size();
    }

    @Override
    public long importUnits(Long unitId, List<UnitInfo> units) {
        UnitInfo parent = unitInfoMapper.selectByPrimaryKey(unitId);
        for (UnitInfo info : units) {
            Long uId =  info.getUnitId();
            info.setRegionCode(parent.getRegionCode());

            info.setDeleteFlag(0);
            info.setSeniorId(unitId);
            info.setUnitTypeId("1");// 默认导入机构为普通部门
            info.setUnitCode(parent.getUnitCode() + uId + "/");
            // 设置垂管标记
            if (StringUtils.isEmpty(info.getManubriumLevel()) && StringUtils.isEmpty(info.getManubriumName())) {
                info.setManubriumFlag(1);
            } else {
                info.setManubriumFlag(0);
            }
            unitInfoMapper.insert(info);
        }
        return unitId;
    }

    @Override
    public long importPower(Long unitId, String unitName, List<PowerImportBean> unitPowers) {
        int result = 0;
        String sql = "select dict_item_name, dict_item_value from sys_dict_item where ";
        //职权类别
        List<SysDictItem> powerTypes = jdbcTemplate.query(sql + "dict_key = 'POWER_TYPES'", new BeanPropertyRowMapper<SysDictItem>(SysDictItem.class));
        //职权状态
        List<SysDictItem> powerStates = jdbcTemplate.query(sql + "dict_key = 'POWER_STATE_TYPES'", new BeanPropertyRowMapper<SysDictItem>(SysDictItem.class));
        //行使层级
//        List<SysDictItem> powerLevels = jdbcTemplate.query(sql + "dict_key = 'POWER_LEVEL_ID'", new BeanPropertyRowMapper<SysDictItem>(SysDictItem.class));
        for (PowerImportBean unitPower : unitPowers) {
            unitPower.setUnitId(unitId);
            unitPower.setUnitName(unitName);
            unitPower.setUnitCode(unitInfoMapper.selectByPrimaryKey(unitId).getUnitCode());
            unitPower.setCreateMethod(2);
            unitPower.setCreateHumanId(SessionHelper.get().getHumanId());
            unitPower.setCreateHuman(SessionHelper.get().getHumanName());
            for (SysDictItem powerType : powerTypes) {
                if (powerType.getDictItemName().equals(unitPower.getPowerTypeName())) {
                    unitPower.setPowerTypeId(powerType.getDictItemValue());
                }
            }

            if (unitPower.getIsCriminal().equals("是")) {
                unitPower.setIsInvolveCriminal(1);
            } else {
                unitPower.setIsInvolveCriminal(0);
            }

            if (unitPower.getIsPublics().equals("是")) {
                unitPower.setIsPublic(1);
            } else {
                unitPower.setIsPublic(0);
            }

            for (SysDictItem powerState : powerStates) {
                if (powerState.getDictItemName().equals(unitPower.getPowerStateName())) {
                    unitPower.setPowerStateId(powerState.getDictItemValue());
                }
            }

//            for (SysDictItem powerLevel : powerLevels) {
//                if (powerLevel.getDictItemName().equals(unitPower.getPowerLevelName())) {
//                    unitPower.setPowerLevelId(powerLevel.getDictItemValue());
//                }
//            }
            result = unitPowerMapper.insert(unitPower);
        }
        return new Long(result);
    }

    @Override
    public PageInfo<UnitPowerBean> getUnitPowersByID(UnitPowerCriteriaBean unitPowerCriteriaBean) {
        PageInfo<UnitPowerBean> page = PageHelper.startPage(unitPowerCriteriaBean.getPageNum(), unitPowerCriteriaBean.getPageSize())
                .doSelectPageInfo(() -> {
                    unitPowerMapper.listUnitPowerPage(unitPowerCriteriaBean);
                });
        for (UnitPowerBean powerBean : page.getList()) {
            powerBean.setPowerBasis(powerBasisMapper.getPowerBasisByPowerId(powerBean.getPowerId()));
            powerBean.setIsRelevance(powerBean.getPowerBasis().size() <1 ? 0 : 1);
        }
        return page;
    }

    @Override
    public PageInfo<UnitSupervise> getUnitSuperviseByID(UnitPowerCriteriaBean unitPowerCriteriaBean) {

        UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(unitPowerCriteriaBean.getUnitId());
        PageInfo<UnitSupervise> page = PageHelper.startPage(unitPowerCriteriaBean.getPageNum(), unitPowerCriteriaBean.getPageSize())
                .doSelectPageInfo(() -> {
                    unitSuperviseMapper.listPage(unitInfo.getSocialCreditCode(),unitInfo.getUnitId());
                });
        page.getList().forEach(v->{
            v.setSupUnitName(unitInfo.getUnitName());
        });
        return page;
    }

    @Override
    public PageInfo<UnitInspect> getUnitInspectByID(UnitPowerCriteriaBean unitPowerCriteriaBean) {
        PageInfo<UnitInspect> page = PageHelper.startPage(unitPowerCriteriaBean.getPageNum(), unitPowerCriteriaBean.getPageSize())
                .doSelectPageInfo(() -> {
                    unitInspectMapper.listPage(unitPowerCriteriaBean.getUnitId());
                });
        return page;
    }

    @Override
    public PageInfo<UnitPermit> getUnitPermitByID(UnitPowerCriteriaBean unitPowerCriteriaBean) {
        PageInfo<UnitPermit> page = PageHelper.startPage(unitPowerCriteriaBean.getPageNum(), unitPowerCriteriaBean.getPageSize())
                .doSelectPageInfo(() -> {
                    unitPermitMapper.listPage(unitPowerCriteriaBean.getUnitId());
                });
        return page;
    }

    @Override
    public Map<String, Integer> getUnitStatData(Long unitId) {
        UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(unitId);

        String sql = "select count(*) from unit_power where unit_id = ?";
        Integer powerCount = jdbcTemplate.queryForObject(sql, Integer.class, unitId);
        sql = "select count(*) from unit_permit where permit_unit_id = ?";
        Integer permitCount = jdbcTemplate.queryForObject(sql, Integer.class, unitId);
        sql = "select count(*) from unit_inspect where unit_id = ?";
        Integer inspectCount = jdbcTemplate.queryForObject(sql, Integer.class, unitId);
        sql = "SELECT COUNT(*) FROM (SELECT * FROM unit_supervise WHERE  sup_code in  (SELECT sup_code FROM  unit_supervise_claim WHERE social_credit_code = ?) UNION SELECT * FROM unit_supervise WHERE sup_unit_id = ?)a";
        Integer superviseCount = jdbcTemplate.queryForObject(sql, Integer.class, unitInfo.getSocialCreditCode(),unitId);
        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("powerCount", powerCount);
        resultMap.put("permitCount", permitCount);
        resultMap.put("inspectCount", inspectCount);
        resultMap.put("superviseCount", superviseCount);
        return resultMap;
    }

    @Override
    public PageInfo<UnitInfo> listUnitPage(UnitCriteriaBean criteria) {

        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId());
        UnitInfo unitInfo = getRegionInfo(unit.getRegionCode(), false);
        criteria.setRegionCode(unitInfo.getRegionCode());
        criteria.setUnitId(unit.getUnitId());
        criteria.setUnitCode(unit.getUnitCode());
        PageInfo<UnitInfo> page = PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize())
                .doSelectPageInfo(() -> {
                    unitInfoMapper.listPage(criteria);
                });

        List<UnitInfo> unitAreas = systemCacheService.loadUnitAreas();
        Map unitNatureTypeMap = MapUtils.invertMap(systemCacheService.listDictItemMap(SystemConst.UNIT_NATURE_TYPE));
        Map unitLevelMap = MapUtils.invertMap(systemCacheService.listDictItemMap(SystemConst.UNIT_LEVEL));
        Map unitTypeMap = MapUtils.invertMap(systemCacheService.listDictItemMap(SystemConst.UNIT_TYPE));

        List<UnitInfo> list = page.getList();
        // 0909 修改 查看父级单位下所有机构和同领域机构
        //加载当前机构下的人员信息
        // 使用字典表进行翻译
        for (UnitInfo u : list) {
            u.setUnitNatureId(unitNatureTypeMap.get(u.getUnitNatureId()) == null ? ""
                    : unitNatureTypeMap.get(u.getUnitNatureId()).toString());
            u.setUnitLevel(
                    unitLevelMap.get(u.getUnitLevel()) == null ? "" : unitLevelMap.get(u.getUnitLevel()).toString());
            u.setUnitTypeId(
                    unitTypeMap.get(u.getUnitTypeId()) == null ? "" : unitTypeMap.get(u.getUnitTypeId()).toString());

            if (StringUtils.isEmpty(u.getRegionName())) {
                for (UnitInfo area : unitAreas) {
                    if (area.getRegionCode().equals(u.getRegionCode())) {
                        u.setRegionName(area.getUnitName());
                        break;
                    }
                }
            }
        }

        return page;
    }

    private String getUnitDomains(Long unitID) {
        List<UnitDomain> domainLists = getDomainLists(unitID);
        List<String> list = new ArrayList<>();
        for (UnitDomain unitDomain : domainLists) {
            list.add(unitDomain.getSubDomainTypeId().toString());
        }
        return StringUtils.join(list, ",");
    }

    @Override
    public List<Map<String, Object>> getUnitLevelStat(Integer isSupervise, Long unitID) {

        String unitTypeFilter = " and unit_type_id in (2,4)  ";
        if (isSupervise == 1) {
            unitTypeFilter = "and unit_type_id in (5,6)  ";
        }

        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String unitFilter = getUnitFilterString(unitID, unit);
        String filter = getDomainFilterString(unit);

        String sql = "SELECT a.*,b.count from "
                + "(SELECT a.dict_item_name as levelName,a.dict_item_value as levelID, b.dict_item_name as type_name,b.dict_item_value as typeID ,a.display_order from "
                + "(SELECT * from  sys_dict_item WHERE dict_key ='UNIT_LEVEL') a ,(SELECT * from  sys_dict_item WHERE dict_key ='UNIT_TYPE' and dict_item_value in('2','4')) b) a "
                + " LEFT JOIN (SELECT unit_level,unit_type_id,count(*) as count from unit_info where delete_flag !=1  "
                + unitTypeFilter + filter + unitFilter
                + " and unit_type_id in(2,4) GROUP BY unit_level,unit_type_id) b "
                + "on a.levelID = b.unit_level and a.typeID = b.unit_type_id order by levelID";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    private String getDomainFilterString(UnitInfo unit) {
        String filter = "";
        if (!"0".equals(unit.getUnitTypeId())) {
            String unitDomains = getUnitDomains(unit.getUnitId());
            if (StringUtils.isNotEmpty(unitDomains)) {
                filter = " and unit_id in ( select unit_id from unit_domain where sub_domain_type_id in (" + unitDomains
                        + ") ) ";
            }
        }
        return filter;
    }

    @Override
    public List<Map<String, Object>> getUnitNatureStat(Integer isSupervise, Long unitID) {
        String unitTypeFilter = " and unit_type_id in (2,4)  ";
        if (isSupervise == 1) {
            unitTypeFilter = "and unit_type_id in (5,6)  ";
        }
        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String unitFilter = getUnitFilterString(unitID, unit);
        String filter = getDomainFilterString(unit);
        String sql = "SELECT dict_item_name,count from "
                + "(SELECT * from  sys_dict_item WHERE dict_key ='UNIT_NATURE_TYPE') a LEFT JOIN  "
                + "(SELECT unit_nature_id ,count(*) as count FROM unit_info where delete_flag !=1 " + unitTypeFilter
                + filter + unitFilter + " GROUP BY unit_nature_id) b on a.dict_item_value = b.unit_nature_id ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getUnitAreaStat(Integer isSupervise, Long unitID) {
        String unitTypeFilter = " and unit_type_id in (2,4)  ";
        if (isSupervise == 1) {
            unitTypeFilter = "and unit_type_id in (5,6)  ";
        }
        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        int length = unit.getRegionCode().length();
        length = length + 2;
        String unitFilter = getUnitFilterString(unitID, unit);
        String filter = getDomainFilterString(unit);

        String sql = "SELECT a.unit_name as dict_item_name,b.count from "
                + "(SELECT * from  unit_info WHERE LENGTH(region_code)=" + length
                + " and unit_type_id=0 and region_code like '" + unit.getRegionCode() + "%' and delete_flag !=1) a LEFT JOIN "
                + "(SELECT regionCode,count(*) as count from (SELECT LEFT(region_code," + length
                + ") as regionCode from unit_info WHERE delete_flag !=1 " + unitTypeFilter + filter + unitFilter
                + " ) t GROUP BY regionCode) b " + "on a.region_code = b.regionCode";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    private String getUnitFilterString(Long unitID, UnitInfo unit) {
        String unitFilter = "";
        if (unitID != null) {
            unitFilter = "and unit_code like '" + unitInfoMapper.selectByPrimaryKey(unitID).getUnitCode() + "%'";
        } else {
            UnitInfo unitInfo = getRegionInfo(unit.getRegionCode(), false);
            unitFilter = "and unit_code like '" + unitInfo.getUnitCode() + "%'";
        }
        return unitFilter;
    }

    @Override
    public List<Map<String, Object>> getLawSubjectStat(Long unitID) {
        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String unitFilter = getUnitFilterString(unitID, unit);
        String filter = getDomainFilterString(unit);
        String sql = "SELECT dict_item_name,count from "
                + "(SELECT * from  sys_dict_item WHERE dict_key ='UNIT_SUBJECT_TYPE') a LEFT JOIN  "
                + "(SELECT subject_type ,count(*) as count FROM unit_info where delete_flag !=1 " + filter + unitFilter
                + " GROUP BY subject_type) b on a.dict_item_value = b.subject_type ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getEntrustUnitStat(Long unitID) {
        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String unitFilter = getUnitFilterString(unitID, unit);
        String filter = getDomainFilterString(unit);
        String sql = "SELECT dict_item_name,count from "
                + "(SELECT * from  sys_dict_item WHERE dict_key ='UNIT_ENTRUST_TYPE') a LEFT JOIN  "
                + "(SELECT entrust_type_id ,count(*) as count FROM unit_info where delete_flag !=1 " + filter
                + unitFilter + " GROUP BY entrust_type_id) b on a.dict_item_value = b.entrust_type_id ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getEntrustNatureStat(Long unitID) {
        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String unitFilter = getUnitFilterString(unitID, unit);
        String filter = getDomainFilterString(unit);
        String sql = "SELECT dict_item_name,count from "
                + "(SELECT * from  sys_dict_item WHERE dict_key ='UNIT_ENTRUST_NATURE_TYPE') a LEFT JOIN  "
                + "(SELECT entrust_nature_id ,count(*) as count FROM unit_info where delete_flag !=1 " + filter
                + unitFilter + " GROUP BY entrust_nature_id) b on a.dict_item_value = b.entrust_nature_id ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getSupUnitLevelStat(Long unitID) {
        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String unitFilter = getUnitFilterString(unitID, unit);
        String filter = getDomainFilterString(unit);
        String sql = "SELECT dict_item_name,count from "
                + "(SELECT * from  sys_dict_item WHERE dict_key ='UNIT_LEVEL') a LEFT JOIN  "
                + "(SELECT unit_level ,count(*) as count FROM unit_info where delete_flag !=1 and unit_type_id in (5,6) "
                + filter + unitFilter + "  GROUP BY unit_level) b on a.dict_item_value = b.unit_level ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<Map<String, Object>> getInnerSupUnitLevelStat(Long unitID) {
        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String unitFilter = getUnitFilterString(unitID, unit);
        String filter = getDomainFilterString(unit);
        String sql = "SELECT dict_item_name,count from "
                + "(SELECT * from  sys_dict_item WHERE dict_key ='SUPERVISE_UNIT_LEVEL') a LEFT JOIN  "
                + "(SELECT sup_unit_level ,count(*) as count FROM unit_info where delete_flag !=1 " + filter
                + unitFilter + " and unit_type_id = 6  GROUP BY sup_unit_level) b on a.dict_item_value = b.sup_unit_level ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public Map<String, Object> getUnitAreaStatForScreen(Integer isSupervise, Long regionid) {

        String unitTypeFilter = " and unit_type_id in (2,4)  ";
        if (isSupervise == 1) {
            unitTypeFilter = " and unit_type_id in (5,6) ";
        } else if (isSupervise == 2) {
            unitTypeFilter = " and unit_type_id = 2 ";
        }
        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String humanFilter = "AND LENGTH(region_code)=4";
        if (regionid != null && regionid != 1) {
            humanFilter = "AND senior_id = '" + regionid + "'";
            unit = unitInfoMapper.selectByPrimaryKey(regionid);
        }
        String regionFilter = "LEFT (region_code, 4) AS region_code";
        if (regionid != null && regionid != 1) {
            regionFilter = "region_code";
        }
        UnitInfo unitInfo = getRegionInfo(unit.getRegionCode(), false);
        String unitFilter = getUnitFilterString(regionid, unit);
        String filter = getDomainFilterString(unit);

        String sql = "SELECT a.unit_id as regionid,a.unit_name AS regionname,a.region_code as regioncode,a.senior_id as seniorid ,b.count as sumnum from"
                + "(SELECT * from  unit_info WHERE  unit_type_id=0 " + humanFilter + ") a LEFT JOIN "
                + "(SELECT region_code,count(*) as `count` from (SELECT " + regionFilter
                + " from unit_info WHERE delete_flag !=1 " + unitTypeFilter + filter + unitFilter
                + " ) t GROUP BY region_code) b " + "on a.region_code = b.region_code";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

        List<SysDictItem> itemList = sysDictService.loadDictByDictItemValue(unitInfo.getUnitTypeId(), "UNIT_TYPE");

        Map<String, Object> returnList = new HashMap<>();
        Map<String, Object> statMap = new HashMap<>();
        Map<String, Object> regionMap = new HashMap<>();
        list.forEach(v -> {
            List<Map<String, Object>> typeList = new ArrayList<>();
            Map<String, Object> typeMap = new HashMap<>();
            v.putIfAbsent("sumnum", "0");
            v.put("regioncode", regionIdFormat(v.get("regioncode").toString()));
            itemList.forEach(j -> {
                typeMap.put("code", j.getDictItemValue());
                typeMap.put("name", j.getDictItemName());
                typeMap.put("num", v.get("sumnum"));
            });
            typeList.add(typeMap);
            v.put("types", typeList);
        });
        regionMap.put("regionid", unitInfo.getUnitId());
        regionMap.put("regioncode", regionIdFormat(unitInfo.getRegionCode()));
        regionMap.put("regionname", unitInfo.getUnitName());
        final int[] i = {0};
        list.forEach(sun -> {
            i[0] += Integer.parseInt(sun.get("sumnum").toString());
        });
        regionMap.put("sumnum", i[0]);
        regionMap.put("seniorid", unitInfo.getSeniorId());
        statMap.put("children", list);
        statMap.put("region", regionMap);
        returnList.put("stat", statMap);
        return returnList;
    }

    @Override
    public Integer getUnitCount(Long unitID, Integer isSupervise) {
        String unitTypeFilter = " and unit_type_id in (2,4)  ";
        if (isSupervise == 1) {
            unitTypeFilter = " and unit_type_id = 5 ";
        }
        UnitInfo unit = unitInfoMapper
                .selectByPrimaryKey(SessionHelper.get().getUnitId() == 0 ? 1 : SessionHelper.get().getUnitId());
        String unitFilter = getUnitFilterString(unitID, unit);
        String filter = getDomainFilterString(unit);
        String sql = "SELECT count(*) as count FROM unit_info where delete_flag !=1 " + unitTypeFilter + filter
                + unitFilter;
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public List<UnitInfo> loadArea(String value) {
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(value)) {
            criteria.andLike("unitName", value + "%");
        }
        criteria.andEqualTo("deleteFlag", 0);
        criteria.andEqualTo("unitTypeId", 0);
        List<UnitInfo> unitInfos = unitInfoMapper.selectByExample(example);
        return unitInfos;
    }

    /**
     * 导入功能
     */
    @Override
    public boolean setUnitPowerValuesTem(MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        try {
            List<TemporaryPowerExcel> storeFlowDataExcelREQS = ExcelImportUtil.importExcel(file.getInputStream(), TemporaryPowerExcel.class, importParams);
            storeFlowDataExcelREQS.forEach(v -> {
                TemporaryPower power = new TemporaryPower();
                BeanUtils.copyProperties(v, power);
                temporaryPowerMapper.insert(power);
            });
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                file.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    public boolean setUnitDomainValues() {
        System.out.println("开始" + System.currentTimeMillis());
        List<UnitDomain> unitDomains = new ArrayList<>();
        System.out.println("unit_info" + System.currentTimeMillis());
        String doMainSql = "SELECT  a.*, b.dict_item_name AS domain_type_name FROM  (SELECT u.unit_id, u.unit_name, d.dict_item_value AS sub_domain_type_id,  d.dict_item_name AS sub_domain_type_name,    d.senior_id AS domain_type_id   FROM    unit_info u,    sys_dict_item d   WHERE INSTR(     u.unit_name,     d.dict_item_name    ) > 0   AND d.dict_key = 'UNIT_DOMAIN'   AND d.senior_id IS NOT NULL  and u.import_batch in ('2019110518','2019110519') ) a,  sys_dict_item b WHERE  a.domain_type_id = b.dict_item_value AND b.dict_key = 'UNIT_DOMAIN' AND b.senior_id IS NULL";
        List<Map<String, Object>> domainList = jdbcTemplate.queryForList(doMainSql);
        System.out.println("domain" + System.currentTimeMillis());
        if (domainList.size() > 0) {
            domainList.forEach(u -> {
                String insterSql = "INSERT  INTO unit_domain (unit_id, domain_type_id, domain_type_name, `sub_domain_type_id`, `sub_domain_type_name`)  VALUES(" + u.get("unit_id") + ", " +
                        " '" + u.get("domain_type_id") + "', '" + u.get("domain_type_name") + "', '" + u.get("sub_domain_type_id") + "', '" + u.get("sub_domain_type_name") + "');";
                jdbcTemplate.execute(insterSql);
            });
        }
        System.out.println(System.currentTimeMillis());
        return true;

    }

    @Override
    public boolean setUnitPowerValues() {
        System.out.println("开始" + System.currentTimeMillis());
        System.out.println("unit_info" + System.currentTimeMillis());
        String doMainSql = "SELECT a.*, s.dict_item_value AS power_type_id " +
                "FROM(SELECT t.`power_name`, t.`power_type_id` AS power_type_name,t.`law_item_content`,i.`unit_name`,t.`duty_list`,t.`duty_basis`,i.unit_id,t.power_id FROM " +
                "temporary_power t,unit_info i WHERE INSTR(i.unit_name, t.unit_name) > 0 AND i.unit_level = '02' AND i.delete_flag !=1" +
                "" +
                " ) a, sys_dict_item s " +
                "WHERE s.dict_key = 'POWER_TYPE' " +
                "AND INSTR(s.dict_item_name,a.power_type_name) > 0;";


        List<Map<String, Object>> domainList = jdbcTemplate.queryForList(doMainSql);
        System.out.println("domain" + System.currentTimeMillis());
        if (domainList.size() > 0) {
            domainList.forEach(u -> {
                String insterSql = "INSERT INTO `unit_power` " +
                        "(`power_name`, `power_type_id`, `power_type_name`, `is_involve_criminal`, `power_state_id`, `power_state_name`, `law_item_content`, `unit_id`, `unit_name`, `duty_list`, `duty_basis`)  " +
                        "VALUES ('" + u.get("power_name") + "', '" + u.get("power_type_id") + "', '" + u.get("power_type_name") + "', '0', '01', '在用',  '" + u.get("law_item_content") + "', '" + u.get("unit_id") + "', '" + u.get("unit_name") + "', '" + u.get("duty_list") + "', '" + u.get("duty_basis") + "');";
                jdbcTemplate.execute(insterSql);
            });
        }
        System.out.println(System.currentTimeMillis());
        return true;
    }

    @Override
    public List<Map<String, Object>> getUnitInfoForProvince(Long unitId) {
        String doMainSql = "SELECT unit_id,unit_name,region_code,senior_id FROM unit_info WHERE  unit_type_id = 0 AND delete_flag != 1 AND senior_id = " + unitId + "";
        List<Map<String, Object>> domainList = jdbcTemplate.queryForList(doMainSql);
        return domainList;
    }

    @Override
    public boolean setUnitInfoValues(MultipartFile file) {
        //根据file得到Workbook,主要是要根据这个对象获取,传过来的excel有几个sheet页
        try {
            Workbook hssfWorkbook = ExcelHelper.getWorkBook(file);
            ImportParams params = new ImportParams();
            String pName = "";
            int numSheet = 0;
//            表头在第几行
//            params.setTitleRows(1);
            //距离表头中间有几行不要的数据
//            params.setStartRows(1);
            //第几个sheet页
            params.setStartSheetIndex(numSheet);
            //验证数据
            params.setNeedVerfiy(true);
                //按级别插入行政区划
            List<UnitInfoExcel> excelList = ExcelHelper.xlsx2List(file.getInputStream(),
                    new String[]{"id", "cityName", "districtName", "streetName", "unitName", "supUnitName", "entrustOfficeName"
                            , "innerSupUnitName", "seniorName"}, UnitInfoExcel.class, numSheet, 1);
            //第一个sheet为执法主体 先新增上级单位  根据市是否为空 判断 上级单位的行政区划
            //新增行政区划
            System.out.println(System.currentTimeMillis());
            addAdministrative(excelList);
            System.out.println(System.currentTimeMillis());

            List<UnitInfoExcel> cityList = excelList.stream().filter(t -> StringUtils.isNotBlank(t.getCityName())).collect(Collectors.toList());
            Map<String, List<UnitInfoExcel>> unitType = cityList.stream().collect(Collectors.groupingBy(UnitInfoExcel::getCityName));
            if (unitType.size() > 0) {
                for (Map.Entry<String, List<UnitInfoExcel>> entry : unitType.entrySet()) {
                    pName = entry.getKey();
                    break;
                }
            }
            //直属一级单位(直属无上级机构单位)
            List<UnitInfoExcel> blankList = excelList.stream().filter(t -> StringUtils.isBlank(t.getSupUnitName()) && StringUtils.isBlank(t.getDistrictName())).collect(Collectors.toList());
            Map<String, List<UnitInfoExcel>> blankGroup = blankList.stream().collect(Collectors.groupingBy(UnitInfoExcel::getUnitName));
            //子级单位或县级直属单位
            List<UnitInfoExcel> filterList = excelList.stream().filter(t -> isNotBlank(t.getSupUnitName()) || isNotBlank(t.getDistrictName())).collect(Collectors.toList());
            //子级单位
            List<UnitInfoExcel> thList = filterList.stream().filter(t -> isNotBlank(t.getSupUnitName()) && StringUtils.isBlank(t.getDistrictName())).collect(Collectors.toList());
            Map<String, List<UnitInfoExcel>> cityGroup = thList.stream().collect(Collectors.groupingBy(UnitInfoExcel::getSupUnitName));
            //县级直属单位
            List<UnitInfoExcel> siList = filterList.stream().filter(t -> isNotBlank(t.getDistrictName()) && StringUtils.isBlank(t.getSupUnitName())).collect(Collectors.toList());
            Map<String, List<UnitInfoExcel>> siGroup = siList.stream().collect(Collectors.groupingBy(UnitInfoExcel::getDistrictName));
            List<UnitInfoExcel> wuList = filterList.stream().filter(t -> isNotBlank(t.getDistrictName()) && isNotBlank(t.getSupUnitName())).collect(Collectors.toList());
            Map<String, List<UnitInfoExcel>> wuGroup = wuList.stream().collect(Collectors.groupingBy(UnitInfoExcel::getSupUnitName));

            List<String> str = new ArrayList<>();
            blankGroup.forEach((k, v) -> str.add(k));
            //新增一级
            logger.debug("用时"+System.currentTimeMillis());

            saveUnitInfo(blankGroup, 2, pName);
            logger.debug("用时"+System.currentTimeMillis());
            //新增二级
            Map<String, List<UnitInfoExcel>> listMap = new HashMap<>();
            Map<String, List<UnitInfoExcel>> hashMap = new HashMap<>();
            for (Map.Entry<String, List<UnitInfoExcel>> entry : cityGroup.entrySet()) {
                if (str.contains(entry.getKey())) {
                    listMap.put(entry.getKey(), entry.getValue());
                } else {
                    hashMap.put(entry.getKey(), entry.getValue());
                }
            }
            saveUnitInfo(listMap, 4, pName);
            logger.debug("用时"+System.currentTimeMillis());
            saveUnitInfo(hashMap, 1, pName);
            logger.debug("用时"+System.currentTimeMillis());
            saveUnitInfo(siGroup, 1, pName);
            logger.debug("用时"+System.currentTimeMillis());
            saveUnitInfo(wuGroup, 4, pName);
            logger.debug("用时"+System.currentTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                file.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    private void addAdministrative(List<UnitInfoExcel> excelList) {

        Map<String, List<UnitInfoExcel>> collect = excelList.stream().collect(Collectors.groupingBy(e -> fetchGroup(e)));
        Map<String, String> map = new HashMap<>();

        for (Map.Entry<String, List<UnitInfoExcel>> entry : collect.entrySet()) {
            String[] typeKey = entry.getKey().trim().split("#");
            map.put("city", typeKey[0]);
            map.put(typeKey[1], typeKey[0]);
        }
        if (isNotBlank(map.get("city"))) {
            List<UnitInfo> list = isExist(map.get("city"), null);
            Example example = new Example(DicRegion.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("regionName", map.get("city"));
            List<DicRegion> regionList = dicRegionMapper.selectByExample(example);
            DicRegion dicRegion = new DicRegion();
            if (regionList.size() > 0) {
                dicRegion = regionList.get(0);
            }
            UnitInfo parent = new UnitInfo();
            List<UnitInfo> unitInfos = new ArrayList<>();
            if (list.size() == 0) {
                UnitInfo info = new UnitInfo();
                List<UnitInfo> unitInfos1 = new ArrayList<>();
                info.setIsLawOrgans(1);
                info.setUnitName(map.get("city"));
                info.setShortName(map.get("city"));
                info.setUnitTypeId("0");
                info.setUnitLevel("03");
                info.setSeniorId(1L);
                info.setUnitCode("/1/");
                info.setRegionCode(dicRegion.getRegionCode());
                info.setRegionName(dicRegion.getRegionName());
                unitInfos1.add(info);
                parent = save(unitInfos1,1);
                UnitInfo unitInfo = new UnitInfo();
                List<UnitInfo> unitInfos2 = new ArrayList<>();
                unitInfo.setIsLawOrgans(1);
                unitInfo.setUnitName("直属部门");
                unitInfo.setShortName("直属部门");
                unitInfo.setUnitTypeId("0");
                unitInfo.setUnitLevel("03");
                unitInfo.setSeniorId(parent.getUnitId());
                unitInfo.setUnitCode(parent.getUnitCode());
                unitInfo.setRegionCode(dicRegion.getRegionCode()+"01");
                unitInfo.setRegionName("直属部门");
                unitInfos2.add(unitInfo);
                save(unitInfos2,1);
            }else if (list.get(0).getUnitName().equals("广西壮族自治区")){
                List<UnitInfo> unitInfos2 = new ArrayList<>();
                UnitInfo unitInfo = new UnitInfo();
                unitInfo.setIsLawOrgans(1);
                unitInfo.setUnitName("直属部门");
                unitInfo.setShortName("直属部门");
                unitInfo.setUnitTypeId("0");
                unitInfo.setUnitLevel("02");
                unitInfo.setSeniorId(list.get(0).getUnitId());
                unitInfo.setUnitCode(list.get(0).getUnitCode());
                unitInfo.setRegionCode(list.get(0).getRegionCode()+"15");
                unitInfo.setRegionName("直属部门");
                unitInfos2.add(unitInfo);
                save(unitInfos2,1);
            }
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (!entry.getKey().equals("city") && !entry.getKey().equals("null")) {
                    UnitInfo info = new UnitInfo();
                    List<UnitInfo> list1 = isExist(entry.getKey(), parent.getUnitId());
                    if (list1.size() == 0) {
                        Example dicExample = new Example(DicRegion.class);
                        Example.Criteria exampleCriteria = dicExample.createCriteria();
                        exampleCriteria.andEqualTo("seniorRegionCode", parent.getRegionCode());
                        exampleCriteria.andEqualTo("regionName", entry.getKey());
                        List<DicRegion> regionChildList = dicRegionMapper.selectByExample(dicExample);
                        DicRegion dicRegion1 = new DicRegion();
                        if (regionChildList.size() > 0) {
                            dicRegion1 = regionChildList.get(0);
                        }
                        info.setIsLawOrgans(1);
                        info.setUnitName(entry.getKey());
                        info.setShortName(entry.getKey());
                        info.setUnitTypeId("0");
                        info.setUnitLevel("04");
                        info.setSeniorId(parent.getUnitId());
                        info.setUnitCode(parent.getUnitCode());
                        info.setRegionCode(dicRegion1.getRegionCode());
                        info.setRegionName(dicRegion1.getRegionName());
                        unitInfos.add(info);
                    }
                }
            }
            save(unitInfos,2);
        }
    }

    private String regionIdFormat(String regionId) {
        int n = 6;
        if (StringUtils.isNotBlank(regionId) && regionId.length() < n) {
            return regionId + String.format("%1$0" + (n - regionId.length()) + "d", 0);
        }
        return regionId;
    }

    @Override
    public void adjust(HumanUnitAdjustBean bean) {
        //跟新机构上级机构编码


        String unitCode = jdbcTemplate.queryForObject("SELECT unit_code from unit_info WHERE unit_id = " + bean.getMoveUnitId() + "", String.class);

        int length = unitCode.length();

        // 更新所有部门节点的unit_code和region_code
        jdbcTemplate
                .update("update unit_info t1, unit_info t2 set  t1.unit_code = concat(t2.unit_code," + bean.getMoveUnitId() + ", SUBSTR(t1.unit_code," + length + ")), "
                        + "t1.region_code = t2.region_code where t2.unit_id = ? and t1.unit_code like '" + unitCode + "%' ", bean.getUnitId());
        //更新选择节点的senior_id
        jdbcTemplate
                .update("update unit_info set senior_id = ? where unit_id  =" + bean.getMoveUnitId() + "", bean.getUnitId());


        unitCode = jdbcTemplate.queryForObject("SELECT unit_code from unit_info WHERE unit_id  = " + bean.getMoveUnitId() + "", String.class);
        //更新人员unit_code
        jdbcTemplate
                .update("update human_info t1, unit_info t2 set t1.unit_code = t2.unit_code where t1.unit_id = t2.unit_id and t2.unit_code like '" + unitCode + "%'");
    }

    @Override
    public Long confirm(long unitId) {
        UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(unitId);
        unitInfo.setIsConfirm(1);
        unitInfoMapper.updateByPrimaryKey(unitInfo);
        return unitId;
    }

    @Override
    public Map<String, Object> checkContainChild(Long unitID, Integer isSupervise) {
        Map<String, Object> result = new HashMap<>();

        String unitFilter = " and unit_type_id = 5 ";
        if (isSupervise == 0) {
            unitFilter = " and unit_type_id in (2,4,6) ";
        }

        String humanTypeFilter = " and human_type = '01'  ";
        if (isSupervise == 1) {
            humanTypeFilter = " and human_type = '02' ";
        }


        UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(unitID);
        String sql = "select count(*) from unit_info where delete_flag = 0 " + unitFilter + " and unit_id != " + unitID + " and unit_code like '" + unitInfo.getUnitCode() + "%'";
        Integer unitCount = jdbcTemplate.queryForObject(sql, Integer.class);
        sql = "select count(*) from human_info where delete_flag = 0 " + humanTypeFilter + " and unit_id = " + unitID;
        Integer humanCount = jdbcTemplate.queryForObject(sql, Integer.class);

        result.put("unitCount", unitCount);
        result.put("humanCount", humanCount);
        return result;
    }

    private static String fetchGroupKey(UnitInfoExcel info) {
        return info.getDistrictName() + "#" + info.getStreetName();
    }

    private static String fetchEntrustKey(UnitInfoExcel info) {
        return info.getDistrictName() + "#" + info.getEntrustOfficeName();
    }

    private static String fetchGroup(UnitInfoExcel info) {
        return info.getCityName() + "#" + info.getDistrictName();
    }

    private static String fetchGroupAllKey(UnitInfoExcel info) {
        return info.getCityName() + "#" + info.getDistrictName() + "#" + info.getStreetName();
    }

    private static String fetchGroupSupKey(UnitInfoExcel info) {
        return info.getUnitName() + "#" + info.getSupUnitName();
    }

    private UnitInfo saveUnitInfo(Map<String, List<UnitInfoExcel>> map, Integer type, String pName) {
        UnitInfo pInfo = new UnitInfo();
        for (Map.Entry<String, List<UnitInfoExcel>> entry : map.entrySet()) {
            List<UnitInfo> list = new ArrayList<>();
            //保存父级单位
            if (type ==2){
                List<UnitInfo> infoList = isExist(pName, null);
                list = isExist("直属部门",infoList.get(0).getUnitId());
            }
            UnitInfo parent = new UnitInfo();
            if (list.size() > 0) {
                parent = list.get(0);
            }
            UnitInfo info = new UnitInfo();
            if (StringUtils.isNotBlank(entry.getKey())) {
                entry.getKey().replace(" ", " ");
                info.setIsLawOrgans(1);
                info.setUnitName(entry.getKey());
                info.setUnitLevel(parent.getUnitLevel() == null ? "02" : parent.getUnitLevel());
                info.setShortName(entry.getKey());
                info.setUnitTypeId("2");
                pInfo = saveUnitInfo(info, parent.getUnitId());
                if (entry.getValue().size()>1 || type == 4){
                    info.setSeniorId(pInfo.getUnitId());
                    info.setRegionName(pInfo.getUnitName());
                    info.setUnitCode(pInfo.getUnitCode());
                    saveUnitInfo1(info, entry.getValue(), pInfo.getUnitId());
                }
            }
        }
        return pInfo;
    }

    private UnitInfo saveUnitInfo(UnitInfo info, Long pId) {
        //保存父级单位
        info.setDeleteFlag(YesNoEnum.NO.getCode());
        long unitId = jdbcTemplate.queryForObject("select max(unit_id)+1 from unit_info", Long.class);
        info.setUnitId(unitId);
        info.setDisplayOrder(unitId);
        //查询是否存在该机构
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("deleteFlag", 1);
        criteria.andEqualTo("unitName", info.getUnitName());
        example.orderBy("displayOrder").asc();
        List<UnitInfo> unitInfo = unitInfoMapper.selectByExample(example);
        if (unitInfo.size() == 0) {
            UnitInfo parent = unitInfoMapper.selectByPrimaryKey(pId == null ? 1L : pId);
            if (null != parent) {
                info.setSeniorName(parent.getSeniorName());
                info.setUnitCode(parent.getUnitCode() + unitId + "/");
                info.setSeniorId(parent.getUnitId());
                info.setRegionName(parent.getUnitName());
                info.setRegionCode(parent.getRegionCode());
            }
            info.setSubjectType("01");
            info.setUnitNatureId("01");
            info.setManubriumFlag(0);
            info.setSupUnitLevel("01");
            info.setImportBatch(DateHelper.dateToString(new Date(), DateHelper.patternB));
            unitInfoMapper.insert(info);
            //新增管理员
            createOneLevelAdministrator(info);
            return unitInfoMapper.selectByPrimaryKey(unitId);
        } else {
            return unitInfo.get(0);
        }
    }

    private UnitInfo saveUnitInfo1(UnitInfo info, List<UnitInfoExcel> excels, Long pId) {
        List<UnitInfo> list = new ArrayList<>();
        for (UnitInfoExcel excel : excels) {
            UnitInfo unitInfo = new UnitInfo();
            BeanUtils.copyProperties(info, unitInfo);
            if (StringUtils.isBlank(excel.getStreetName()) && StringUtils.isBlank(excel.getDistrictName())) {
                //插入省级单位执法机关
                List<UnitInfo> flag = isExist(excel.getUnitName() == null ? "" : excel.getUnitName(), null);
                if (flag.size() == 0) {
                    unitInfo.setUnitLevel("02");
                }else {
                    continue;
                }
            } else if (StringUtils.isBlank(excel.getStreetName()) && isNotBlank(excel.getDistrictName())) {
                //插入市级单位执法机关
                unitInfo.setUnitLevel("04");
            } else if (isNotBlank(excel.getStreetName()) && isNotBlank(excel.getDistrictName())) {
                //插入三级单位执法机关
                unitInfo.setUnitLevel("05");
            }
            unitInfo.setUnitNatureId("01");
            unitInfo.setUnitName(excel.getUnitName());
            unitInfo.setShortName(excel.getUnitName());
            unitInfo.setUnitTypeId("2");
            UnitInfo parent = unitInfoMapper.selectByPrimaryKey(pId == null ? 1L : pId);
            if (null != parent) {
                unitInfo.setRegionCode(parent.getRegionCode());
                unitInfo.setRegionName(parent.getRegionName());
            }
            list.add(unitInfo);
        }
        save(list,2);
        return info;
    }

    private UnitInfo save(List<UnitInfo> list,Integer type) {
        UnitInfo unitInfo = new UnitInfo();
        for (UnitInfo unitInfo1 :list){
            unitInfo1.setDeleteFlag(YesNoEnum.NO.getCode());
            long sonId = jdbcTemplate.queryForObject("select max(unit_id)+1 from unit_info", Long.class);
            unitInfo1.setUnitId(sonId);
            unitInfo1.setDisplayOrder(sonId);
            unitInfo1.setUnitNatureId("01");
            unitInfo1.setSubjectType("01");
            unitInfo1.setUnitCode(unitInfo1.getUnitCode() + sonId + "/");
            unitInfo1.setSupUnitLevel("01");
            unitInfo1.setImportBatch(DateHelper.dateToString(new Date(), DateHelper.patternB));
            //查询是否存在该机构
            List<UnitInfo> unitInfos = isExist(unitInfo1.getUnitName(), unitInfo1.getSeniorId());
            if (unitInfos.size() > 0 && type == 1) {
                return unitInfos.get(0);
            } else if (unitInfos.size() > 0 && type == 2){
                continue;
            }else {
                createOneLevelAdministrator(unitInfo1);
                unitInfoMapper.insert(unitInfo1);
                unitInfo = unitInfoMapper.selectByPrimaryKey(sonId);

            }
        }
        return unitInfo;
    }

    private List<UnitInfo> isExist(String name, Long pId) {
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("deleteFlag", 1);
        criteria.andEqualTo("unitName", name);
        criteria.andEqualTo("seniorId", pId);
        example.orderBy("displayOrder").asc();
        return unitInfoMapper.selectByExample(example);
    }

    private boolean isNotBlank(String str) {
        if (StringUtils.isNotBlank(str) && !str.equals("null")) {
            return true;
        }
        return false;
    }

    private void createOneLevelAdministrator(UnitInfo info) {
        long humanId = jdbcTemplate.queryForObject("select max(human_id)+1 from human_info", Long.class);
        HumanInfo humanInfo = new HumanInfo();
        humanInfo.setUnitId(info.getUnitId());
        humanInfo.setUnitName(info.getUnitName());
        humanInfo.setUnitCode(info.getUnitCode());
        humanInfo.setHumanId(humanId);
        humanInfo.setDeleteFlag(0);
        humanInfo.setLoginFlag(1);
        humanInfo.setHumanType("00");// 管理员默认人员类型
        humanInfo.setDisplayOrder((int) humanId);
        String name = info.getUnitName() + "管理员";
        humanInfo.setHumanName(name);
        int userNameCounts = humanInfoMapper.countByUserNameAndHumanId(name);
        if (userNameCounts > 0) {
//            return;
            humanInfo.setUserName(name + humanId);
        } else {
            humanInfo.setUserName(name);
        }
        String defaultHumanPassword = systemCacheService.loadSysConfigItem(
                SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD_CONFIG);
        if (StringUtils.isEmpty(defaultHumanPassword)) {
            defaultHumanPassword = SystemConst.DEFAULT_HUMAN_LOGIN_PASSWORD;
        }
        humanInfo.setHumanPassword(
                DigestUtils.md5Hex(defaultHumanPassword.concat(String.valueOf(humanId))).toUpperCase());
        humanInfoMapper.insert(humanInfo);
        // 添加管理员用户对应的岗位
        HumanRole hr = new HumanRole();
        hr.setHumanId(humanId);
        // 获取机构类型对应的岗位信息
        String defaultAdminRoleId = systemCacheService.loadSysConfigItem(
                SystemConst.DEFAULT_ADMIN_ROLE_ID_PRIFIX + info.getUnitTypeId());
        if (StringUtils.isEmpty(defaultAdminRoleId)) {
            defaultAdminRoleId = SystemConst.DEFAULT_ADMIN_ROLE_ID;
        }
        if (!StringUtils.isEmpty(defaultAdminRoleId)) {
            hr.setRoleId(Long.valueOf(defaultAdminRoleId));
            humanRoleMapper.insert(hr);
        }
    }

    @Override
    public List<PowerBasis> saveUpdatePowerBasis(List<PowerBasis> basisList) {
        for (PowerBasis powerBasis : basisList) {
            if (powerBasis.getCauseId() != null) {
                Example example = new Example(PowerBasis.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("powerId", powerBasis.getPowerId());
                criteria.andEqualTo("causeId", powerBasis.getCauseId());
                powerBasisMapper.deleteByExample(example);
            }
            if (powerBasis.getSetBasisCode() != null && powerBasis.getSetBasisCode() != "") {
                Example example = new Example(PowerBasis.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("powerId", powerBasis.getPowerId());
                criteria.andEqualTo("setBasisCode", powerBasis.getSetBasisCode());
                powerBasisMapper.deleteByExample(example);
            }
            powerBasisMapper.insert(powerBasis);
        }
        return powerBasisMapper.getPowerBasisByPowerId(basisList.get(0).getPowerId());
    }

    @Override
    public List<PowerBasis> deletePowerBasisById(List<PowerBasis> basisList) {
        for (PowerBasis powerBasis : basisList) {
            if (powerBasis.getCauseId() != null) {
                Example example = new Example(PowerBasis.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("powerId", powerBasis.getPowerId());
                criteria.andEqualTo("causeId", powerBasis.getCauseId());
                powerBasisMapper.deleteByExample(example);
            }
            if (powerBasis.getSetBasisCode() != null && powerBasis.getSetBasisCode() != "") {
                Example example = new Example(PowerBasis.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("powerId", powerBasis.getPowerId());
                criteria.andEqualTo("setBasisCode", powerBasis.getSetBasisCode());
                powerBasisMapper.deleteByExample(example);
            }
        }
        return powerBasisMapper.getPowerBasisByPowerId(basisList.get(0).getPowerId());
    }

    public Integer containDirectUnit(Long unitID) {
        Example example = new Example(UnitInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("deleteFlag", 1);
        criteria.andEqualTo("seniorId", unitID);
        criteria.andEqualTo("unitTypeId", 0);
        criteria.andLike("unitName", "直属%");
        List<UnitInfo> units = unitInfoMapper.selectByExample(example);
        return units.size();
    }

    @Override
    public List<Map<String, Object>> getUnitPowerListForLawCode(String unitCode, Long regionid) {
        String regionFilter = "LEFT (region_code, 4) AS region_code";
        if (regionid != null && regionid != 1) {
            regionFilter = "region_code as region_code";
        }
        String doMainSql = "SELECT " + regionFilter + ",pb.punish_basis_code AS  fz_code,ui.senior_id ,ui.unit_id FROM unit_power up LEFT JOIN unit_info ui ON up.unit_id = ui.unit_id LEFT JOIN power_basis pb ON up.power_id = pb.power_id WHERE ui.unit_code LIKE '" + unitCode + "%' AND ui.region_code <> '45'  AND pb.punish_basis_code IS NOT NULL";
        return jdbcTemplate.queryForList(doMainSql);
    }

    @Override
    public boolean saveDicRegion(String regionJson) {
        Gson gson = new Gson();
        Map<String, List<DicRegionBean>> dealMap = gson.fromJson(regionJson, java.util.HashMap.class);
        List<DicRegionBean> dicRegions = new ArrayList<>();
        dealMap.forEach((k, v) -> {
                List<DicRegionBean> list = gson.fromJson(gson.toJson(v), new TypeToken<ArrayList<DicRegionBean>>() {
                }.getType());
                for (DicRegionBean region : list) {
                    region.setRegionCode(region.getId());
                    region.setRegionName(region.getText());
                    region.setSeniorRegionCode(k);
                if (k.length() == 1) {
                    region.setRegionLevel(2);
                } else if (k.length() == 2) {
                    region.setRegionLevel(3);
                } else if (k.length() == 4) {
                    region.setRegionLevel(4);
                } else if (k.length() == 6) {
                    region.setRegionLevel(5);
                }
                    dicRegions.add(region);
                }
            });
//        List<DicRegion> dicRegions = new ArrayList<>();
//        dealMap.forEach((k, v) -> {
//            List<DicRegion> list = gson.fromJson(gson.toJson(v), new TypeToken<ArrayList<DicRegion>>() {
//            }.getType());
//            for (DicRegion region : list) {
//                region.setSeniorRegionCode(k);
//                if (k.length() == 2) {
//                    region.setRegionLevel(3);
//                } else if (k.length() == 4) {
//                    region.setRegionLevel(4);
//                } else if (k.length() == 6) {
//                    region.setRegionLevel(5);
//                }
//                dicRegions.add(region);
//            }
//        });
        dicRegions.forEach(v -> dicRegionMapper.insert(v));
        return true;
    }

    @Override
    public List<SelectItem> loadAddress() {
        List<SelectItem> selectItems = new ArrayList<>();
        List<SelectItem> items = new ArrayList<>();//下一级
        List<SelectItem> list = dicRegionMapper.selectAllAddress();
        for (SelectItem selectItem : list) {
            if (selectItem.getLevel() == 4) {
                selectItem.setLeaf(true);
                items.add(selectItem);
            } else {
                selectItems.add(selectItem);
            }
        }
        list.clear();
        list = traversalAddress(selectItems, items, 3);
        List<SelectItem> item = new ArrayList<>();
        for(SelectItem selectItem : list) {
            if (selectItem.getValue().equals("45")) {
                item.add(selectItem);
            }
        }
        return item;
    }

    @Override
    public boolean setUnitDomainValue() {
        List<Long> ids = jdbcTemplate.queryForList("SELECT	p.unit_id FROM	unit_info p LEFT JOIN unit_info c ON c.senior_id = p.unit_id WHERE	c.unit_type_id = 6",
                Long.class);
//        List<Map<String, Object>> list =  jdbcTemplate.queryForList(sql);
        String idFilter = "WHERE unit_id  in (" + StringUtils.join(ids, ",") + ")";

        String filter = " AND senior_id in (" + StringUtils.join(ids, ",") + ")";
        String doSql = "SELECT * FROM  unit_domain " + idFilter + "";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(doSql);
        String psql = "SELECT unit_id,senior_id FROM unit_info WHERE unit_type_id = 6 " + filter + "";
        List<Map<String, Object>> forList = jdbcTemplate.queryForList(psql);
        List<Map<String, Object>> domainList = new ArrayList<>();
        forList.forEach(v -> {
            mapList.forEach(u -> {
                if (v.get("senior_id").equals(u.get("unit_id"))) {
                    Map<String, Object> map = new HashMap<>();
                    map.putAll(u);
                    map.put("unit_id", v.get("unit_id"));
                    domainList.add(map);
                }
            });

        });
        if (domainList.size() > 0) {
            domainList.forEach(u -> {
                try {
                    String insterSql = "INSERT  INTO unit_domain (unit_id, domain_type_id, domain_type_name, `sub_domain_type_id`, `sub_domain_type_name`)  VALUES(" + u.get("unit_id") + ", " +
                            " '" + u.get("domain_type_id") + "', '" + u.get("domain_type_name") + "', '" + u.get("sub_domain_type_id") + "', '" + u.get("sub_domain_type_name") + "');";
                    jdbcTemplate.execute(insterSql);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return false;
    }

    private List<SelectItem> traversalAddress(List<SelectItem> selectItems, List<SelectItem> items, int level) {
        List<SelectItem> select = new ArrayList<>();//下级
        List<SelectItem> list = new ArrayList<>();//上级
        if (level != 1) {
            for (SelectItem selectItem : selectItems) {//上级遍历
                if (selectItem.getLevel() == level) {
                    List<SelectItem> selectItemList = new ArrayList<>();
                    for (SelectItem item : items) {//下级遍历
                        if (item.getSeniorId().equals(selectItem.getValue())) {//当属于上级时
                            selectItemList.add(item);//存放在空list中
                        }
                    }
                    selectItem.setChildren(selectItemList);//保存当前上级地址的所有下级地址
                    if (selectItemList.size() == 0) {
                        selectItem.setLeaf(true);
                    }
                    select.add(selectItem);//保存下级
                } else {
                    list.add(selectItem);//保存上级
                }
            }
        } else {
            return items;
        }
        return traversalAddress(list, select, level - 1);
    }

    public UnitPowerBean addPowerBasis(UnitPowerBean unitPowerBean) {
        UnitPower unitPower = new UnitPower();
        List<PowerBasis> list = unitPowerBean.getPowerBasis();
        BeanUtils.copyProperties(unitPowerBean, unitPower);
        unitPower.setCreateMethod(3);
        unitPower.setCreateHumanId(SessionHelper.get().getHumanId());
        unitPower.setCreateHuman(SessionHelper.get().getHumanName());
        unitPower.setUnitCode(unitInfoMapper.selectByPrimaryKey(unitPower.getUnitId()).getUnitCode());
        // 判断新增或编辑
        if (unitPowerBean.getPowerId() != null) {
            unitPowerMapper.updateByPrimaryKey(unitPower);
            powerBasisMapper.deletePowerById(unitPower.getPowerId());
        } else {
            unitPowerMapper.insertUnitPower(unitPower);
            unitPowerBean.setPowerId(unitPower.getPowerId());
        }
        // 判断法律法规是否存在。
        if (list != null && list.size() > 0) {
            for (PowerBasis powerBasis : list) {
                powerBasis.setPowerId(unitPower.getPowerId());
                powerBasis.setCreateHumanId(SessionHelper.get().getHumanId());
                powerBasis.setCreateHuman(SessionHelper.get().getHumanName());
                powerBasisMapper.insert(powerBasis);
            }
        }
        return unitPowerBean;
    }

    public int deletePowerById(Integer powerId) {
        return unitPowerMapper.deleteByPrimaryKey(powerId) + powerBasisMapper.deletePowerById(powerId);
    }

    public UnitPowerBean loadPowerById(Integer powerId) {
        UnitPowerBean unitPowerBean = unitPowerMapper.loadPowerById(powerId);
        String sql = "select * from power_basis where power_id = " + powerId + ";";
        List<PowerBasis> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<PowerBasis>(PowerBasis.class));
        unitPowerBean.setPowerBasis(list);
        return unitPowerBean;
    }

    @Override
    public boolean setSubjectIdValue() {
        String sql = "SELECT * FROM `unit_info` WHERE `unit_type_id` IN  (4,6) AND senior_id IS not NULL AND  delete_flag !=1 ";
        List<UnitInfo> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(UnitInfo.class));
        list.forEach(v->{
            UnitInfo unitInfo = findUnitType(v.getSeniorId());
            v.setSubjectId(unitInfo.getUnitId());
            v.setSubjectName(unitInfo.getUnitName());
            unitInfoMapper.updateByPrimaryKey(v);
        });
        return false;
    }

    @Override
    public boolean setSubjectIdValues() {
        String sql = "SELECT * FROM `unit_info` WHERE `unit_type_id` IN  (2,5)";
        List<UnitInfo> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(UnitInfo.class));
        list.forEach(v->{
            v.setSubjectId(v.getUnitId());
            v.setSubjectName(v.getUnitName());
            unitInfoMapper.updateByPrimaryKey(v);
        });
        return false;
    }

    private UnitInfo findUnitType(Long seniorId) {
        UnitInfo unitInfo;
        unitInfo = unitInfoMapper.selectByPrimaryKey(seniorId);
        if (!unitInfo.getUnitTypeId().equals("2") && !unitInfo.getUnitTypeId() .equals("5")){
            unitInfo = findUnitType(unitInfo.getSeniorId());
        }
        return unitInfo;
    }

    @Override
    public String loadAreaId(Long id) {
        UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(id);
        if (!unitInfo.getUnitTypeId().equals("0")) {
            if (StringUtils.isEmpty(unitInfo.getUnitAreaId())) {
                unitInfo = unitInfoMapper.selectByPrimaryKey(unitInfo.getSubjectId());
            }
        }
        return unitInfo.getUnitAreaId();
    }

    @Override
    public Map<String, Object> getLawDynamicsInfo() {
        UnitInfo SessionUnit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId());
        Map<String, Object> returnMap = new HashMap<>();
        //行政处罚
        Map<String, Object> map = new HashMap<>();
        String doMainSql = "SELECT * FROM (SELECT count(*) AS simple FROM `punish`.rec_punish WHERE rec_type_id = '01'  AND unit_code LIKE '" + SessionUnit.getUnitCode() + "%' AND state_id <> 99 )b,"
                + "(SELECT count(*) AS normal  FROM `punish`.rec_punish WHERE rec_type_id = '02' AND unit_code LIKE '" + SessionUnit.getUnitCode() + "%' AND state_id <> 99) c ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(doMainSql);
        if (list != null) {
            list.forEach(map::putAll);
        }
        //行政检查
        Map<String, Object> checkMap = new HashMap<>();
        String checkSql = "SELECT count(*) AS `check` FROM `check`.rec_check where unit_code LIKE '"+SessionUnit.getUnitCode()+"%' ";
        List<Map<String,Object>> checkList = jdbcTemplate.queryForList(checkSql);
        if (checkList!= null){
            checkList.forEach(checkMap::putAll);
        }
        //行政强制
        Map<String, Object> forceMap = new HashMap<>();
        String force = "SELECT count(*) AS `force` FROM `forces`.rec_force where unit_code LIKE '"+SessionUnit.getUnitCode()+"%' AND  state_id <> 99";
        List<Map<String,Object>> forceList = jdbcTemplate.queryForList(force);
        if (forceList!= null){
            forceList.forEach(forceMap::putAll);
        }
        returnMap.putAll(map);
        returnMap.putAll(checkMap);
        returnMap.putAll(forceMap);
        return  returnMap;
    }

    @Override
    public Map<String, Object> getDepartmentInfo() {
        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId());
        //职权、监管事项、检查事项 使用登陆者所属主体数据
        UnitInfo subjectInfo = unit;
        if (!unit.getUnitTypeId().equals("0")){
            subjectInfo = unitInfoMapper.selectByPrimaryKey(unit.getSubjectId());
        }

        Map<String, Object> returnMap = new HashMap<>();
        //执法人数
        String sql = "select count(*) from human_info hu where hu.unit_code like '" + unit.getUnitCode() + "%'  AND  hu.delete_flag = 0 AND  hu.is_law_human = 1 AND  hu.human_type != '00'";
        Integer humanCount = jdbcTemplate.queryForObject(sql, Integer.class);
        //总职权信息
        String powerSql = "SELECT count(*) AS `authority` FROM unit_power ui LEFT JOIN unit_info uf ON ui.unit_id = uf.unit_id WHERE uf.delete_flag != 1 AND uf.unit_code like '" + subjectInfo.getUnitCode() + "%' ";
        Integer powerCount = jdbcTemplate.queryForObject(powerSql, Integer.class);
        //已履行职权信息(统计类别为行政处罚、行政强制)
        //已履行职权信息(统计类别为行政处罚、行政强制)
        // 取出所有行政处罚中 已被关联的 unit_id 和punish_basis_code 并根据unit_id  和punish_basis_code 分组
        // 取出所有unit_id 为上述list中，且 类型为行政处罚的所有已被关联的职权的 unit_id 和punish_basis_code 并根据unit_id  和punish_basis_code 分组
        // 已被关联的所有机构的职权 存在于行政处罚中的数量 定义为履职数量
        String powerFulfilSql = "SELECT rp.subject_id AS  unit_id,rc.punish_basis_code FROM  punish.rec_punish rp LEFT JOIN punish.rec_cause rc ON rp.rec_id = rc.rec_id  WHERE  " +
                "rc.punish_basis_code IN (SELECT  punish_basis_code FROM(  SELECT t1.unit_name,t2.punish_basis_code,t1.unit_id,t3.unit_code  FROM unit_power t1,  " +
                "(SELECT power_id,  punish_basis_code FROM  power_basis  WHERE  cause_id IS NOT NULL  GROUP BY  punish_basis_code  ) t2,  unit_info t3 WHERE  t1.power_id = t2.power_id AND t3.unit_code LIKE  '" +  unit.getUnitCode() + "%'" +
                "  AND t1.power_type_id = '02'  AND t3.unit_id = t1.unit_id  ) t ORDER BY punish_basis_code)  " +
                " AND rp.unit_code LIKE  '" +  unit.getUnitCode() + "%'" +
                "GROUP BY rp.unit_id,rc.punish_basis_code";
        List<UnitPowerDynamic> list = jdbcTemplate.query(powerFulfilSql, new BeanPropertyRowMapper<>(UnitPowerDynamic.class));
        Map<Long, List<UnitPowerDynamic>> punishGroup = list.stream().collect(Collectors.groupingBy(UnitPowerDynamic::getUnitId));
        // 取出所有unit_id
        List<Long> unitIdList = list.stream().map(UnitPowerDynamic::getUnitId).distinct().collect(Collectors.toList());
        String filter = "AND up.unit_id in  ('" + StringUtils.join(unitIdList, "','") + "')";
        String sql1 = "SELECT up.unit_id,pb.punish_basis_code FROM unit_power up  LEFT JOIN power_basis pb ON up.power_id = pb.power_id  WHERE pb.cause_id IS NOT NULL  AND up.power_type_id = '02' "+filter+" GROUP BY up.unit_id,pb.punish_basis_code ORDER BY up.unit_id DESC";
        List<UnitPowerDynamic> powers = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(UnitPowerDynamic.class));
        Map<Long, List<UnitPowerDynamic>> powerGroup = powers.stream().collect(Collectors.groupingBy(UnitPowerDynamic::getUnitId));
        List<UnitPowerDynamic> unitPowers = new ArrayList<>();
        punishGroup.forEach((k, v) -> {
            powerGroup.forEach((p, g) -> {
                if (k.equals(p)) {
                    List<UnitPowerDynamic> list3 = v.stream()
                            .map(map -> g.stream()
                                    .filter(m -> Objects.equals(m.getPunishBasisCode(), map.getPunishBasisCode()))
                                    .findFirst().map(m -> map).orElse(null))
                            .filter(Objects::nonNull).collect(Collectors.toList());
                    unitPowers.addAll(list3);
                }
            });
        });
        //已关联职权
        String powerRelationSql = "SELECT SUM(num) FROM  (SELECT COUNT(*) AS  num FROM(SELECT t1.unit_name, t1.unit_id,t3.unit_code FROM unit_power t1,(SELECT power_id FROM power_basis WHERE cause_id IS NOT NULL GROUP BY power_id) t2,unit_info t3 " +
                "WHERE t1.power_id = t2.power_id  AND t3.unit_code LIKE '" + subjectInfo.getUnitCode() + "%' AND t3.unit_id = t1.unit_id ) t GROUP BY  t.unit_id)a;";
        Integer powerRelationCount = jdbcTemplate.queryForObject(powerRelationSql, Integer.class);
        //行政处罚、行政强制 总职权信息
        String powerPunishOrForceSql = "SELECT  SUM(num) FROM (SELECT COUNT(*) AS  num FROM unit_power up LEFT JOIN unit_info ui ON up.unit_id = ui.unit_id WHERE ui.delete_flag <> 1 AND up.power_type_id in ('02','03') AND ui.unit_code LIKE '" + subjectInfo.getUnitCode() + "%' GROUP BY ui.unit_id ORDER BY ui.unit_name)a;";
        Integer powerPunishOrForceCount = jdbcTemplate.queryForObject(powerPunishOrForceSql, Integer.class);
        //行政处罚、行政强制 关联职权信息
        String powerPunishOrForceRelaSql = "SELECT  SUM(num) FROM (SELECT COUNT(*) AS  num FROM(SELECT t1.unit_name, t1.unit_id,t3.unit_code FROM unit_power t1,(SELECT power_id FROM power_basis WHERE cause_id IS NOT NULL GROUP BY power_id) t2,unit_info t3 " +
                "WHERE t1.power_id = t2.power_id AND t1.power_type_id in ('02','03') AND t3.unit_code LIKE '" + subjectInfo.getUnitCode() + "%' AND t3.unit_id = t1.unit_id ) t GROUP BY  t.unit_id)a;";
        Integer powerPunishOrForceRelaCount = jdbcTemplate.queryForObject(powerPunishOrForceRelaSql, Integer.class);
        //总检查事项
        String checkSql = "SELECT count(*) AS `check` FROM unit_inspect ui LEFT JOIN unit_info uf ON ui.unit_id = uf.unit_id WHERE uf.delete_flag != 1 AND uf.unit_code like '" + subjectInfo.getUnitCode() + "%' ";
        Integer checkCount = jdbcTemplate.queryForObject(checkSql, Integer.class);
        //已关联检查事项数
        String checkFulfilSql = "SELECT count(*) AS `check` FROM unit_inspect ui LEFT JOIN unit_info uf ON ui.unit_id = uf.unit_id WHERE uf.delete_flag != 1 AND uf.unit_code like '" + subjectInfo.getUnitCode() + "%' ";
        Integer checkFulfilCount = jdbcTemplate.queryForObject(checkFulfilSql, Integer.class);
        //总监管事项数
        String serSql = "SELECT social_credit_code FROM unit_info WHERE unit_code like '" + subjectInfo.getUnitCode() + "%'  AND unit_type_id = 2  AND delete_flag = 0 AND  social_credit_code != ''";
        List<Map<String, Object>> serList = jdbcTemplate.queryForList(serSql);
        List<String> socialList = new ArrayList<>();
        serList.forEach(v->{
            socialList.add(v.get("social_credit_code").toString());
        });
        String socialFilter;
        Integer superviseCount = 0;
        if (socialList.size() > 0){
            socialFilter = "social_credit_code in  ('" + StringUtils.join(socialList, "','") + "')";
            String superviseSql = "SELECT COUNT(*) FROM (SELECT * FROM unit_supervise WHERE  sup_code in  (SELECT sup_code FROM  unit_supervise_claim WHERE "+socialFilter+") UNION SELECT us.* FROM unit_supervise us LEFT JOIN unit_info ui ON ui.unit_id = us.sup_unit_id  WHERE ui.unit_code like '" + subjectInfo.getUnitCode() + "%'  )a";
            superviseCount = jdbcTemplate.queryForObject(superviseSql, Integer.class);
        }
        //已关联监管事项数(包含行政处罚 行政检察)
        String superviseFulfilSql = "SELECT  SUM(num) FROM (SELECT COUNT(*) AS  num FROM punish.rec_punish WHERE unit_code like '" + subjectInfo.getUnitCode() + "%' AND supervise_item_code != '' GROUP by supervise_item_code)a";
        Integer superviseFulfilCount = jdbcTemplate.queryForObject(superviseFulfilSql, Integer.class);
        String superCheckSql = "SELECT  SUM(num) FROM (SELECT COUNT(*) AS  num  FROM `check`.rec_check WHERE unit_code like '" + subjectInfo.getUnitCode() + "%'  AND supervise_item_implement_code != '' GROUP by supervise_item_implement_code)a";
        Integer superCheckCount = jdbcTemplate.queryForObject(superCheckSql, Integer.class);

        int i = superCheckCount==null?0:superCheckCount;
        int j = superviseFulfilCount==null?0:superviseFulfilCount;
        returnMap.put("humanCount",humanCount);
        returnMap.put("powerCount",powerCount);
        returnMap.put("powerRelationCount",powerRelationCount);
        returnMap.put("powerPunishOrForceCount",powerPunishOrForceCount);
        returnMap.put("powerPunishOrForceRelaCount",powerPunishOrForceRelaCount);
        returnMap.put("powerFulfilCount",unitPowers.size());
        returnMap.put("checkCount",checkCount);
        returnMap.put("checkFulfilCount",0);
        returnMap.put("superviseCount",superviseCount);
        returnMap.put("superviseFulfilCount",i+j);
        return returnMap;
    }

    @Override
    public Pager getDynamicUnitInfo(DynamicUnitExcel dynamicUnitExcel) {
        List<DynamicUnitExcelExport>  units = getExcelList(dynamicUnitExcel,false);
        Pager pager = new Pager(dynamicUnitExcel.getPageNum(),  units);
        List pageList = Pager.getPagerList();
        Pager returnPage = new Pager();
        returnPage.setCurrentPage(pager.getCurrentPage());
        returnPage.setTotalPage(pager.getTotalPage());
        returnPage.setTotal(pager.getTotal());
        returnPage.setList(pageList);
        return returnPage;
    }
    @Override
    public ResponseEntity<byte[]> exportExcel(HttpServletResponse response, DynamicUnitExcel dynamicUnitExcel){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(exportExcelForByte(dynamicUnitExcel,false), headers, HttpStatus.OK);
    }

    @Override
    public byte[] exportExcelForByte(DynamicUnitExcel dynamicUnitExcel,boolean unitFlag) {
        List<ExcelField> fields = new ArrayList<>();
        fields.add(new ExcelField("单位名称", "subjectName",0));
        fields.add(new ExcelField("执法人数", "human",1));
        fields.add(new ExcelField("职权数", "power",1));
        fields.add(new ExcelField("职权（行政处罚强制）数", "powerPuForce",1));
        fields.add(new ExcelField("职权（行政处罚强制）关联数", "powerPunishOrForceRela",1));
        fields.add(new ExcelField("检查事项数", "check",1));
        fields.add(new ExcelField("监管事项数", "supervise",1));
        fields.add(new ExcelField("行政处罚录入数", "punish",1));
        fields.add(new ExcelField("行政强制录入数", "force",1));
        fields.add(new ExcelField("行政检查录入数", "checkRec",1));
        List<DynamicUnitExcelExport> resultList = getExcelList(dynamicUnitExcel,unitFlag);
        Map<String,Object> map = new HashMap<>();
        map.put("human", resultList.stream().mapToInt(DynamicUnitExcelExport::getHuman).sum());
        map.put("power", resultList.stream().mapToInt(DynamicUnitExcelExport::getPower).sum());
        map.put("powerPuForce", resultList.stream().mapToInt(DynamicUnitExcelExport::getPowerPuForce).sum());
        map.put("owerPunishOrForceRela", resultList.stream().mapToInt(DynamicUnitExcelExport::getPowerPunishOrForceRela).sum());
        map.put("check", resultList.stream().mapToInt(DynamicUnitExcelExport::getCheck).sum());
        map.put("checkRec", resultList.stream().mapToInt(DynamicUnitExcelExport::getCheckRec).sum());
        map.put("supervise", resultList.stream().mapToInt(DynamicUnitExcelExport::getSupervise).sum());
        map.put("force", resultList.stream().mapToInt(DynamicUnitExcelExport::getForce).sum());
        map.put("punish", resultList.stream().mapToInt(DynamicUnitExcelExport::getPunish).sum());

        String subTitle;
        if (StringUtils.isNotBlank(dynamicUnitExcel.getEndDate()) && StringUtils.isNotBlank(dynamicUnitExcel.getStartDate())){
            subTitle = "统计时间： "+DateHelper.dateTimeToStr(DateHelper.getDateBegin(DateHelper.strToDate(dynamicUnitExcel.getStartDate())))+"~"+DateHelper.dateTimeToStr(DateHelper.getDateEnd(DateHelper.strToDate(dynamicUnitExcel.getEndDate())));
        }else  if (StringUtils.isNotBlank(dynamicUnitExcel.getEndDate())){
            subTitle = "截止时间： "+DateHelper.dateTimeToStr(DateHelper.getDateEnd(DateHelper.strToDate(dynamicUnitExcel.getEndDate())));
        }else if(StringUtils.isNotBlank(dynamicUnitExcel.getStartDate())){
            subTitle = "统计时间： "+DateHelper.dateTimeToStr(DateHelper.getDateBegin(DateHelper.strToDate(dynamicUnitExcel.getStartDate())))+"~"+DateHelper.dateTimeToStr(new Date());
        }else {
            subTitle = "截止时间： "+DateHelper.dateTimeToStr(new Date());
        }
        ByteArrayOutputStream bos = (ByteArrayOutputStream) ExcelHelper.exportExcel(resultList,map, "执法监督数据汇总", subTitle, fields,
                DynamicUnitExcelExport.class);
        return bos.toByteArray();
    }

    private List<DynamicUnitExcelExport> getExcelList(DynamicUnitExcel dynamicUnitExcel ,Boolean unitFlag){
        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(unitFlag?1:SessionHelper.get().getUnitId());
        List<DynamicUnitExcelExport> resultList = new ArrayList<>();
        if (unit.getUnitName().indexOf("直属") > -1) {
            Example example = new Example(UnitInfo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("unitTypeId", 0);
            criteria.andEqualTo("unitId", unit.getSeniorId());
            List<UnitInfo> list = unitInfoMapper.selectByExample(example);
            if (list != null && list.size()>0){
                unit = list.get(0);
            }
        }
        if (unit == null){
            return resultList;
        }
        if (!unit.getUnitTypeId().equals("0")){
            Example example = new Example(UnitInfo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andNotEqualTo("regionCode", unit.getRegionCode());
            criteria.andEqualTo("unitTypeId", 0);
            List<UnitInfo> units = unitInfoMapper.selectByExample(example);
            if (units != null && units.size() > 0){
                unit = units.get(0);
            }
        }
        Set<String> unitName = new HashSet<>();
        String regionFilter = "";
        String startFilter = "";
        String endFilter = "";
        if (StringUtils.isNotBlank(dynamicUnitExcel.getRegionCode())){
            String[] strs = dynamicUnitExcel.getRegionCode().split("/");
            dynamicUnitExcel.setRegionCode(strs[strs.length-1]);
            regionFilter = "and ui.region_code like '"+dynamicUnitExcel.getRegionCode() + "%'";
        }
        if (StringUtils.isNotBlank(dynamicUnitExcel.getStartDate())){
            startFilter = "and hu.create_time >= '" + DateHelper.dateTimeToStr(DateHelper.getDateBegin(DateHelper.strToDate(dynamicUnitExcel.getStartDate()))) + "'";
        }
        if (StringUtils.isNotBlank(dynamicUnitExcel.getEndDate())){
            endFilter = "and hu.create_time <= '" +DateHelper.dateTimeToStr(DateHelper.getDateEnd(DateHelper.strToDate(dynamicUnitExcel.getEndDate())))+ "'";
        }
        // 查询机构下人员数量
        String humanSql = "SELECT ui.subject_name,LEFT(ui.region_code,4) AS region_code,COUNT(*) AS `count` FROM human_info hu LEFT JOIN unit_info ui ON hu.unit_id = ui.unit_id WHERE hu.human_type<> '00' AND hu.delete_flag <> 1 AND ui.delete_flag <>1 AND  ui.unit_type_id <> 0 "+regionFilter+" "+startFilter+" "+endFilter+" AND hu.unit_code LIKE  '"+unit.getUnitCode()+"%'  GROUP BY ui.subject_id ORDER BY ui.unit_name;";
        List<Map<String,Object>> humanList = jdbcTemplate.queryForList(humanSql);
        humanList.forEach(v->{
            unitName.add(v.get("subject_name").toString());
        });
        System.out.println(System.currentTimeMillis());
        //查询机构下职权总数
        String powerSql = "SELECT ui.subject_name,LEFT(ui.region_code,4) AS region_code,COUNT(*) AS `count` FROM unit_power hu LEFT JOIN unit_info ui ON hu.unit_id = ui.unit_id WHERE ui.delete_flag <> 1 AND  ui.subject_name != ''"+regionFilter+"  "+startFilter+" "+endFilter+" AND ui.unit_code LIKE  '"+unit.getUnitCode()+"%' GROUP BY ui.subject_id ORDER BY ui.subject_name;";
        List<Map<String,Object>> powerList = jdbcTemplate.queryForList(powerSql);
        powerList.forEach(v->{
            unitName.add(v.get("subject_name").toString());
        });
        System.out.println(System.currentTimeMillis());
        //查询机构下职权（处罚、强制）总数
        String powerPuForceSql = "SELECT ui.subject_name,LEFT(ui.region_code,4) AS region_code,COUNT(*) AS `count`FROM unit_power hu LEFT JOIN unit_info ui ON hu.unit_id = ui.unit_id WHERE ui.delete_flag <> 1 AND hu.power_type_id in ('02','03') AND  ui.subject_name != '' "+regionFilter+"  "+startFilter+" "+endFilter+" AND ui.unit_code LIKE  '"+unit.getUnitCode()+"%'  GROUP BY ui.subject_id ORDER BY ui.unit_name;";
        List<Map<String,Object>> powerPuForceList = jdbcTemplate.queryForList(powerPuForceSql);
        powerPuForceList.forEach(v->{
            unitName.add(v.get("subject_name").toString());
        });
        System.out.println(System.currentTimeMillis());
        //处罚强制 关联数
        String powerPunishOrForceRelaSql = "SELECT  ui.subject_name,LEFT(ui.region_code,4) AS region_code,COUNT(*) AS  `count` FROM(SELECT  *FROM  power_basis  WHERE  EXISTS (  SELECT  *FROM  unit_power  WHERE  power_type_id IN ('02', '03')  AND power_basis.power_id = unit_power.power_id  )  " +
                "GROUP BY power_id) a  LEFT JOIN unit_power hu ON a.power_id = hu.power_id  LEFT JOIN unit_info ui ON ui.unit_id = hu.unit_id  WHERE    ui.subject_name != '' "+regionFilter+" "+startFilter+" "+endFilter+" AND ui.unit_code LIKE  '"+unit.getUnitCode()+"%'  AND  ui.delete_flag <> 1 GROUP BY  ui.subject_id  ORDER BY hu.unit_name;";
        List<Map<String,Object>> powerPunishOrForceRelaList = jdbcTemplate.queryForList(powerPunishOrForceRelaSql);
        powerPunishOrForceRelaList.forEach(v->{
            unitName.add(v.get("subject_name").toString());
        });
        System.out.println(System.currentTimeMillis());
        //检查事项数
        String checkSql = "SELECT ui.subject_name,LEFT(ui.region_code,4) AS region_code,COUNT(*) AS `count` FROM unit_inspect hu LEFT JOIN unit_info ui ON hu.unit_id = ui.unit_id WHERE ui.delete_flag <> 1 "+regionFilter+" "+startFilter+"  "+endFilter+" AND ui.unit_code LIKE  '"+unit.getUnitCode()+"%'  GROUP BY ui.subject_id ORDER BY ui.unit_name;";
        List<Map<String,Object>> checkList = jdbcTemplate.queryForList(checkSql);
        checkList.forEach(v->{
            unitName.add(v.get("subject_name").toString());
        });
        System.out.println(System.currentTimeMillis());
        //监管事项数
        String superviseSql = "SELECT b.sup_unit_name AS subject_name,b.region_code,COUNT(DISTINCT b.sup_code) AS `count`  " +
                "FROM( SELECT hu.sup_unit_name,hu.social_credit_code,hu.sup_code,LEFT(ui.region_code,4) AS region_code FROM unit_supervise hu INNER  JOIN unit_info ui ON ui.unit_id = hu.sup_unit_id "+regionFilter+" "+startFilter+"  "+endFilter+" WHERE hu.social_credit_code != ''AND hu.sup_unit_id != '' AND ui.unit_code LIKE  '"+unit.getUnitCode()+"%'  UNION ALL SELECT ui.unit_name, hu.social_credit_code, hu.sup_code,LEFT(ui.region_code,4) AS region_code FROM  " +
                "unit_supervise_claim hu INNER JOIN unit_info ui ON ui.social_credit_code = hu.social_credit_code INNER JOIN unit_supervise usu ON usu.sup_code = hu.sup_code AND ui.social_credit_code != '' AND hu.social_credit_code != '' "+regionFilter+" "+startFilter+"  "+endFilter+" AND ui.unit_code LIKE  '"+unit.getUnitCode()+"%' ) b  " +
                "GROUP BY b.social_credit_code ORDER BY b.sup_unit_name";
        List<Map<String,Object>> superviseList = jdbcTemplate.queryForList(superviseSql);
        superviseList.forEach(v->{
            unitName.add(v.get("subject_name").toString());
        });
        System.out.println(System.currentTimeMillis());
        //行政处罚录入数
        String punishSql = "SELECT ui.subject_name,LEFT(ui.region_code,4) AS region_code,COUNT(1) AS `count` FROM punish.rec_punish hu LEFT JOIN cda.unit_info ui ON hu.unit_id = ui.unit_id WHERE state_id <> 99  AND  ui.subject_name != ''"+regionFilter+"  "+startFilter+" "+endFilter+" AND  ui.delete_flag <> 1 AND ui.unit_code LIKE  '"+unit.getUnitCode()+"%'  GROUP BY ui.subject_id  ORDER BY ui.unit_name;";
        List<Map<String,Object>> punishList = jdbcTemplate.queryForList(punishSql);
        punishList.forEach(v->{
            unitName.add(v.get("subject_name").toString());
        });
        //行政强制录入数
        String forceSql = "SELECT ui.subject_name,LEFT(ui.region_code,4) AS region_code,COUNT(1) AS `count` FROM forces.rec_force hu  LEFT JOIN cda.unit_info ui ON hu.unit_id = ui.unit_id WHERE state_id <> 99  AND  ui.subject_name != ''"+regionFilter+"  "+startFilter+" "+endFilter+" AND  ui.delete_flag <> 1 AND ui.unit_code LIKE  '"+unit.getUnitCode()+"%'  GROUP BY ui.subject_id  ORDER BY ui.unit_name;";
        List<Map<String,Object>> forceList = jdbcTemplate.queryForList(forceSql);
        forceList.forEach(v->{
            unitName.add(v.get("subject_name").toString());
        });
        //行政检查录入数
        String checkRecSql = "SELECT ui.subject_name,LEFT(ui.region_code,4) AS region_code,COUNT(1) AS `count` FROM `check`.rec_check hu LEFT JOIN cda.unit_info ui ON hu.law_subject_id = ui.unit_id WHERE ui.subject_name != ''"+regionFilter+"  "+startFilter+" "+endFilter+" AND  ui.delete_flag <> 1 AND ui.unit_code LIKE  '"+unit.getUnitCode()+"%'  GROUP BY ui.subject_id  ORDER BY ui.unit_name;";
        List<Map<String,Object>> checkRecList = jdbcTemplate.queryForList(checkRecSql);

        checkRecList.forEach(v->{
            unitName.add(v.get("subject_name").toString());
        });
        List<Map<String,Object>> mapArrayList = new ArrayList<>();
        humanList.forEach(v->{
            unitName.forEach(j->{
                if (j.equals(v.get("subject_name"))){
                    Map<String,Object> map = new HashMap<>();
                    map.put("human",v.get("count")==null?0:v.get("count"));
                    map.put("subjectName",v.get("subject_name"));
                    map.put("regionCode",v.get("region_code"));
                    mapArrayList.add(map);
                }
            });
        });
        powerList.forEach(j->{
            unitName.forEach(v->{
                if (v.equals(j.get("subject_name"))){
                    Map<String,Object> map = new HashMap<>();
                    map.put("power",j.get("count")==null?0:j.get("count"));
                    map.put("subjectName",j.get("subject_name"));
                    map.put("regionCode",j.get("region_code"));
                    mapArrayList.add(map);
                }
            });
        });
        powerPuForceList.forEach(j->{
            unitName.forEach(v->{
                if (v.equals(j.get("subject_name"))){
                    Map<String,Object> map = new HashMap<>();
                    map.put("powerPuForce",j.get("count")==null?0:j.get("count"));
                    map.put("subjectName",j.get("subject_name"));
                    map.put("regionCode",j.get("region_code"));
                    mapArrayList.add(map);
                }
            });
        });
        powerPunishOrForceRelaList.forEach(j->{
            unitName.forEach(v->{
                if (v.equals(j.get("subject_name"))){
                    Map<String,Object> map = new HashMap<>();
                    map.put("powerPunishOrForceRela",j.get("count")==null?0:j.get("count"));
                    map.put("subjectName",j.get("subject_name"));
                    map.put("regionCode",j.get("region_code"));
                    mapArrayList.add(map);
                }
            });
        });
        checkList.forEach(j->{
            unitName.forEach(v->{
                if (v.equals(j.get("subject_name"))){
                    Map<String,Object> map = new HashMap<>();
                    map.put("check",j.get("count")==null?0:j.get("count"));
                    map.put("subjectName",j.get("subject_name"));
                    map.put("regionCode",j.get("region_code"));
                    mapArrayList.add(map);
                }
            });
        });
        superviseList.forEach(v->{
            unitName.forEach(j->{
                if (j.equals(v.get("subject_name"))){
                    Map<String,Object> map = new HashMap<>();
                    map.put("supervise",v.get("count")==null?0:v.get("count"));
                    map.put("subjectName",v.get("subject_name"));
                    map.put("regionCode",v.get("region_code"));
                    mapArrayList.add(map);
                }
            });
        });
        punishList.forEach(v->{
            unitName.forEach(j->{
                if (j.equals(v.get("subject_name"))){
                    Map<String,Object> map = new HashMap<>();
                    map.put("punish",v.get("count")==null?0:v.get("count"));
                    map.put("subjectName",v.get("subject_name"));
                    map.put("regionCode",v.get("region_code"));
                    mapArrayList.add(map);
                }
            });
        });
        forceList.forEach(v->{
            unitName.forEach(j->{
                if (j.equals(v.get("subject_name"))){
                    Map<String,Object> map = new HashMap<>();
                    map.put("force",v.get("count")==null?0:v.get("count"));
                    map.put("subjectName",v.get("subject_name"));
                    map.put("regionCode",v.get("region_code"));
                    mapArrayList.add(map);
                }
            });
        });
        checkRecList.forEach(v->{
            unitName.forEach(j->{
                if (j.equals(v.get("subject_name"))){
                    Map<String,Object> map = new HashMap<>();
                    map.put("checkRec",v.get("count")==null?0:v.get("count"));
                    map.put("subjectName",v.get("subject_name"));
                    map.put("regionCode",v.get("region_code"));
                    mapArrayList.add(map);
                }
            });
        });
        Map<String, List<Map<String, Object>>> glist = mapArrayList.stream().collect(Collectors.groupingBy(e -> e.get("subjectName").toString()));
        List<DynamicUnitExcel> units = new ArrayList<>();
        glist.forEach((k, v) ->{
            Map<String,Object> map = new HashMap<>();
            v.forEach(j->{
                j.remove("subjectName");
                j.forEach((a,b)->{
                    map.put(a,b);
                });
            });
            DynamicUnitExcel entity = JSON.parseObject(JSON.toJSONString(map), DynamicUnitExcel.class);
            entity.setSubjectName(k);
            units.add(entity);
        });
        units.forEach(UnitInfoServiceImpl::nullToEmpty);
        units.forEach(v->{
            if (v.getRegionCode().equals("4515")){
                v.setRegionCode("4500");
            }
        });
        units.forEach(v->{
            DynamicUnitExcelExport export = new DynamicUnitExcelExport();
            export.setHuman(Integer.parseInt(v.getHuman()));
            export.setPower(Integer.parseInt(v.getPower()));
            export.setPowerPuForce(Integer.parseInt(v.getPowerPuForce()));
            export.setPowerPunishOrForceRela(Integer.parseInt(v.getPowerPunishOrForceRela()));
            export.setCheck(Integer.parseInt(v.getCheck()));
            export.setCheckRec(Integer.parseInt(v.getCheckRec()));
            export.setSubjectName(v.getSubjectName());
            export.setSupervise(Integer.parseInt(v.getSupervise()));
            export.setForce(Integer.parseInt(v.getForce()));
            export.setPunish(Integer.parseInt(v.getPunish()));
            resultList.add(export);
        });
        resultList.sort(Comparator.comparing(DynamicUnitExcelExport:: getPunish).reversed());
        return  resultList;
    }

    private static <T> void  nullToEmpty(T bean) {
        Field[] field = bean.getClass().getDeclaredFields();
        for (int j = 0; j < field.length; j++) {     //遍历所有属性
            String name = field[j].getName();    //获取属性的名字
            //将属性的首字符大写，方便构造get，set方法
            name = name.substring(0, 1).toUpperCase() + name.substring(1);
            String type = field[j].getGenericType().toString();    //获取属性的类型
            if (type.equals("class java.lang.String")) {   //如果type是类类型，则前面包含"class "，后面跟类名
                try {
                    Method mGet = bean.getClass().getMethod("get" + name);
                    String value = (String) mGet.invoke(bean);    //调用getter方法获取属性值
                    if (value == null || "".equals(value)) {
                        Method mSet = bean.getClass().getMethod("set" + name, new Class[]{String.class});
                        mSet.invoke(bean, new Object[]{new String("0")});
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public PageInfo<HumanInfo> listHumanInfoPage(HumanInfoCriteriaBean humanInfoCriteriaBean) {
        PageInfo<HumanInfo> page = PageHelper.startPage(humanInfoCriteriaBean.getPageNum(), humanInfoCriteriaBean.getPageSize())
                .doSelectPageInfo(() -> {
                    humanInfoMapper.listHumanInfoPage(humanInfoCriteriaBean);
                });
        return page;
    }

    @Override
    public PageInfo<UnitInfo> listUnitInfoPage(UnitCriteriaBean criteria) {
        UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(criteria.getUnitId());
        criteria.setUnitId(unitInfo.getSubjectId());
        PageInfo<UnitInfo> page = PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize())
                .doSelectPageInfo(() -> {
                    unitInfoMapper.listUnitInfoPage(criteria);
                });
        return page;
    }
    /**
     * 导入南宁市结案表数据
     */
    public boolean importClosingTable(MultipartFile file) {
        // 数据处理
        try {
            //获取时间生成导入批次
            logger.debug("start："+System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
            sdf.applyPattern("yyyy-MM-dd HH");
            Date date = new Date();// 获取当前时间
            String importBatch = sdf.format(date) +"--"+ date.getMinutes() + "";
            //从excel表中取出数据
            logger.debug("startExcel："+System.currentTimeMillis());
            List<ClosingTableExcel> excelList = ExcelHelper.xlsx3List(file.getInputStream(),
                    new String[]{"caseNo", "sourceSubject", "insertSystem", "updateSystem", "caseType", "enforceCause", "caseRegiedate"
                            , "casePunishDate", "punishMoney", "punishContent", "punishKind", "enforceClosedate", "regionCode",
                            "enforcerName", "secodeEnforcerName", "qzcsSqspsx", "sourceKind", "deptName", "punishKindName",
                            "caseContent", "applyzeTime", "proveTime", "surveTime", "lawName", "enforceNum" ,"organizeName" ,"lawContent"}, ClosingTableExcel.class);
            //将行政处罚和行政强制的数据分开
            logger.debug("endExcel："+System.currentTimeMillis());
            List<ClosingTableExcel> recPunish = new ArrayList<>();
            List<ClosingTableExcel> recForce = new ArrayList<>();
            logger.debug("recPunish："+System.currentTimeMillis());
            excelList.forEach(e->{
                switch (e.getCaseType()) {
                    case "01":
                    case "02":
                        recPunish.add(e);
                        break;
                    case "03":
                        e.setCaseType("01");
                        recForce.add(e);
                        break;
                    default:
                        e.setCaseType("02");
                        recForce.add(e);
                        break;
                }
            });
            Map<Integer,List<HumanAndUnit>> humanAndUnitPunish = new HashMap<>();
            recPunish.forEach(it->{
                //当单位名称为空时，将此案卷移交给行政主体。
                String sqlUnitInfo ="select region_code,subject_id,unit_info.unit_id,unit_info.unit_code,human_id,human_name from unit_info,human_info where unit_info.unit_id = human_info.unit_id AND human_info.human_type = '00' AND unit_info.delete_flag = 0 AND unit_info.unit_name = '"+(it.getDeptName() != null?it.getDeptName():it.getOrganizeName())+"'"+"AND  unit_info.subject_name ='"+it.getOrganizeName()+"'";
                //通过行政主体与数据库比较，将数据补充完整
                List<HumanAndUnit> humanAndUnit = jdbcTemplate.query(sqlUnitInfo,new BeanPropertyRowMapper<HumanAndUnit>(HumanAndUnit.class));
                humanAndUnitPunish.put(recPunish.indexOf(it),humanAndUnit);
            });
            //保存返回的rec_id
            List<Long> punishRecID = new ArrayList<>();
            //通过逐条插入返回rec_id
            logger.debug("StartPunish："+System.currentTimeMillis());
            recPunish.forEach((ClosingTableExcel it) ->{
                final String sql ="insert into  `punish`.`rec_punish`(register_doc_num, punish_action_name ," +
                        " create_time, update_time, rec_type_id , subject_name , unit_name , register_date , " +
                        "event_src_id , case_introduce, lawman_name , punish_date , punish_amount , finish_date ,  " +
                        "region_code , punish_doc_num , import_batch, state_id, state_name, is_perfection, subject_id, unit_id, unit_code, create_human_id, create_human_Name,task_num)"
                        + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
                KeyHolder keyHolder = new GeneratedKeyHolder();
                jdbcTemplate.update(
                        new PreparedStatementCreator() {
                            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                                String caseType = "";
                                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                                if(it.getCaseType().equals("01")){
                                    caseType =  "02";
                                }
                                if (it.getCaseType().equals("02")){
                                    caseType = "01";
                                }
                                String lawName = it.getSecodeEnforcerName() == null?it.getEnforcerName():it.getEnforcerName() + "^" + it.getSecodeEnforcerName();
                                String unitName = it.getDeptName() == null?it.getOrganizeName():it.getDeptName();
                                String registerDocNum = it.getCaseNo() == null?it.getCaseNo():it.getCaseNo().replace(" ","");
                                ps.setString(1, registerDocNum);
                                ps.setString(2, it.getSourceSubject());
                                ps.setString(3, it.getInsertSystem());
                                ps.setString(4, it.getUpdateSystem());
                                ps.setString(5, caseType);
                                ps.setString(6, it.getOrganizeName());
                                ps.setString(7, unitName);
                                ps.setString(8, it.getCaseRegiedate());
                                ps.setString(9, it.getSourceKind());
                                ps.setString(10, it.getCaseContent());
                                ps.setString(11, lawName);
                                ps.setString(12, it.getCasePunishDate());
                                ps.setString(13, it.getPunishMoney());
                                ps.setString(14, it.getEnforceClosedate());
                                ps.setString(15, humanAndUnitPunish.get(recPunish.indexOf(it)).get(0).getRegionCode());
                                ps.setString(16, it.getEnforceNum());
                                ps.setString(17, importBatch);
                                ps.setInt(18, 0);
                                ps.setString(19, "正常");
                                ps.setString(20, "0");
                                ps.setLong(21, humanAndUnitPunish.get(recPunish.indexOf(it)).get(0).getSubjectId());
                                ps.setLong(22, humanAndUnitPunish.get(recPunish.indexOf(it)).get(0).getUnitId());
                                ps.setString(23, humanAndUnitPunish.get(recPunish.indexOf(it)).get(0).getUnitCode());
                                ps.setLong(24, humanAndUnitPunish.get(recPunish.indexOf(it)).get(0).getHumanId());
                                ps.setString(25, humanAndUnitPunish.get(recPunish.indexOf(it)).get(0).getHumanName());
                                ps.setString(26, feignClientPunish.calculate(caseType));
                                return ps;
                            }
                        },keyHolder);
                //将返回的rec_id保存起来
                punishRecID.add(keyHolder.getKey().longValue());
            });
            Map<Integer,List<HumanAndUnit>> humanAndUnitForce = new HashMap<>();
            recForce.forEach(it->{
                //当单位名称为空时，将此案卷移交给行政主体。
                String sqlUnitInfo ="select region_code,subject_id,unit_info.unit_id,unit_info.unit_code,human_id,human_name from unit_info,human_info where unit_info.unit_id = human_info.unit_id AND human_info.human_type = '00' AND unit_info.delete_flag = 0 AND unit_info.unit_name = '"+(it.getDeptName() != null?it.getDeptName():it.getOrganizeName())+"'"+"AND  unit_info.subject_name ='"+it.getOrganizeName()+"'";
                //通过行政主体与数据库比较，将数据补充完整
                List<HumanAndUnit> humanAndUnit = jdbcTemplate.query(sqlUnitInfo,new BeanPropertyRowMapper<HumanAndUnit>(HumanAndUnit.class));
                humanAndUnitForce.put(recForce.indexOf(it),humanAndUnit);
            });
            //保存返回的rec_id
            List<Long> forceRecID = new ArrayList<>();
            //导入rec_force表
            logger.debug("StartForce："+System.currentTimeMillis());
            recForce.forEach(it->{
                final String sql = "insert into  `forces`.`rec_force`(rec_type_id , create_time , update_time , subject_name , unit_name , lawman_name , region_code , import_batch,state_id, state_name, is_perfection, subject_id, unit_id, unit_code, create_human_id, create_human_Name,task_num)"
                        + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                KeyHolder keyHolder = new GeneratedKeyHolder();
                jdbcTemplate.update(
                        new PreparedStatementCreator() {
                            String lawName = it.getSecodeEnforcerName() == null?it.getEnforcerName():it.getEnforcerName() + "^" + it.getSecodeEnforcerName();
                            String unitName = it.getDeptName() == null?it.getOrganizeName():it.getDeptName();
                            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                                ps.setString(1, it.getCaseType());
                                ps.setString(2, it.getInsertSystem());
                                ps.setString(3, it.getUpdateSystem());
                                ps.setString(4, it.getOrganizeName());
                                ps.setString(5, unitName);
                                ps.setString(6, lawName);
                                ps.setString(7, humanAndUnitForce.get(recForce.indexOf(it)).get(0).getRegionCode());
                                ps.setString(8, importBatch);
                                ps.setInt(9, 0);
                                ps.setString(10, "正常");
                                ps.setString(11, "0");
                                ps.setLong(12, humanAndUnitForce.get(recForce.indexOf(it)).get(0).getSubjectId());
                                ps.setLong(13, humanAndUnitForce.get(recForce.indexOf(it)).get(0).getUnitId());
                                ps.setString(14, humanAndUnitForce.get(recForce.indexOf(it)).get(0).getUnitCode());
                                ps.setLong(15, humanAndUnitForce.get(recForce.indexOf(it)).get(0).getHumanId());
                                ps.setString(16, humanAndUnitForce.get(recForce.indexOf(it)).get(0).getHumanName());
                                ps.setString(17, feignClientForce.calculate(it.getCaseType()));
                                return ps;
                            }
                        },keyHolder);
                //将返回的rec_id保存起来
                forceRecID.add(keyHolder.getKey().longValue());
            });
            logger.debug("endForce："+System.currentTimeMillis());
            List<Long> causeId = new ArrayList<>();
            recPunish.forEach(it->{
                final String sql = "insert into  `punish`.`rec_cause`(cause_content , punish_content , infringe_basis , punish_basis,rec_id)"
                        + " values (?, ?, ?, ?, ?)";
                KeyHolder keyHolder = new GeneratedKeyHolder();
                jdbcTemplate.update(
                        new PreparedStatementCreator() {
                            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                                ps.setString(1, it.getEnforceCause());
                                ps.setString(2, it.getPunishContent());
                                ps.setString(3, it.getLawName());
                                ps.setString(4, it.getLawContent());
                                ps.setLong(5, punishRecID.get(recPunish.indexOf(it)).longValue());
                                return ps;
                            }
                        },keyHolder);
                //将返回的cause_id保存起来
                causeId.add(keyHolder.getKey().longValue());
            });
            //导入行政强制库，rec_cause表
            jdbcTemplate.batchUpdate("insert into  `forces`.`rec_cause`(cause_content , infringe_basis , punish_basis, rec_id)"
                    + " values (?, ?, ?, ?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ClosingTableExcel it = recForce.get(i);
                    ps.setString(1, it.getEnforceCause());
                    ps.setString(2, it.getLawName());
                    ps.setString(3, it.getLawContent());
                    ps.setLong(4, forceRecID.get(i).longValue());
                }
                @Override
                public int getBatchSize() {
                    return recForce.size();
                }
            });
            //导入rec_force_measure表
            jdbcTemplate.batchUpdate("insert into  `forces`.`rec_force_measure`(measure_type_name, rec_id)"
                    + " values (?,?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ClosingTableExcel it = recForce.get(i);
                    ps.setString(1, it.getQzcsSqspsx());
                    ps.setLong(2, forceRecID.get(i).longValue());
                }
                @Override
                public int getBatchSize() {
                    return recForce.size();
                }
            });
            //导入rec_punish_detail表
            jdbcTemplate.batchUpdate("insert into  `punish`.`rec_punish_detail`(excute_type_id , excute_type_name, rec_id ,cause_id)"
                    + " values (?, ?, ?, ?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ClosingTableExcel it = recPunish.get(i);
                    ps.setString(1, it.getPunishKind());
                    ps.setString(2, it.getPunishKindName());
                    ps.setLong(3, punishRecID.get(i).longValue());
                    ps.setLong(4, causeId.get(i).longValue());
                }
                @Override
                public int getBatchSize() {
                    return recPunish.size();
                }
            });
            //导入rec_punish_investigation表
            jdbcTemplate.batchUpdate("insert into  `punish`.`rec_punish_investigation`(inv_date,rec_id)"
                    + " values (?,?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ClosingTableExcel it = recPunish.get(i);
                    ps.setString(1, it.getSurveTime());
                    ps.setLong(2, punishRecID.get(i).longValue());
                }
                @Override
                public int getBatchSize() {
                    return recPunish.size();
                }
            });
            //导入rec_punish_hearing表
            jdbcTemplate.batchUpdate("insert into  `punish`.`rec_punish_hearing`(stage_date,rec_id)"
                    + " values (?,?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ClosingTableExcel it = recPunish.get(i);
                    ps.setString(1, it.getProveTime());
                    ps.setLong(2, punishRecID.get(i).longValue());
                }
                @Override
                public int getBatchSize() {
                    return recPunish.size();
                }
            });
            //导入rec_punish_inform表
            jdbcTemplate.batchUpdate("insert into  `punish`.`rec_punish_inform`(inform_date,rec_id)"
                    + " values (?,?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ClosingTableExcel it = recPunish.get(i);
                    ps.setString(1, it.getApplyzeTime());
                    ps.setLong(2, punishRecID.get(i).longValue());
                }
                @Override
                public int getBatchSize() {
                    return recPunish.size();
                }
            });
            //导入rec_litigant_info表
            jdbcTemplate.batchUpdate("insert into  `punish`.`rec_litigant_info`(litigant_type_id,litigant_type_name,person_name,company_name,rec_id)"
                    + " values (?,?,?,?,?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ClosingTableExcel it = recPunish.get(i);
                    Object nullObj = null;
                    String sourceSubject = it.getSourceSubject();
                    sourceSubject = sourceSubject.replace("的案件", "");
                    sourceSubject = sourceSubject.replace("关于", "");
                    if(sourceSubject.length() > 3){
                        ps.setString(1, "02");
                        ps.setString(2, "法人");
                        ps.setObject(3,nullObj);
                        ps.setString(4, sourceSubject);
                        ps.setLong(5, punishRecID.get(i).longValue());
                    }else {
                        ps.setString(1, "01");
                        ps.setString(2, "自然人");
                        ps.setString(3,sourceSubject);
                        ps.setObject(4, nullObj);
                        ps.setLong(5, punishRecID.get(i).longValue());
                    }
                }
                @Override
                public int getBatchSize() {
                    return recPunish.size();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                file.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public Map<String, Object> loadAddressByUser() {
        List<String> values = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        UnitInfo unit = unitInfoMapper.selectByPrimaryKey(SessionHelper.get().getUnitId());
        if (unit.getUnitName().indexOf("直属") > -1) {
            Example example = new Example(UnitInfo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("unitId", unit.getSeniorId());
            criteria.andEqualTo("unitTypeId", 0);
            unit = unitInfoMapper.selectByExample(example).get(0);
        }
         Example example = new Example(DicRegion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("regionCode", unit.getRegionCode());
        List<DicRegion> regionList = dicRegionMapper.selectByExample(example);
        DicRegion region = new DicRegion();
        if (regionList.size() > 0){
            region = regionList.get(0);
        }
        if ((region.getRegionLevel() <= 2 || unit.getUnitName().indexOf("直属") > 0)){
            if (Objects.equals(region.getSeniorRegionCode(), "45")){
                values.add(region.getSeniorRegionCode());
                values.add(region.getRegionCode());
                map.put("values",values);
            }else {
                List<DicRegion> list = dicRegionMapper.selectAddressByRegionCode(region.getRegionCode(),"%直属%");
                values.add(list.get(0).getSeniorRegionCode());
                values.add(list.get(0).getRegionCode());
                map.put("values",values);
            }
            if(unit.getUnitTypeId().equals("0")){
                map.put("address",loadAddress());
                return  map;
            }
        }else if (region.getRegionLevel() == 3 && unit.getUnitName().indexOf("直属") < 0){
            UnitInfo unitInfo = unitInfoMapper.selectByPrimaryKey(unit.getSeniorId());
            if (Objects.equals(unitInfo.getRegionCode(), "4515")){
                values.add(region.getSeniorRegionCode());
                values.add(region.getRegionCode());
            }else {
                List<DicRegion> dicRegions = dicRegionMapper.selectAddressByRegionCode(region.getRegionCode(),"%市辖区%");
                values.add(region.getSeniorRegionCode());
                values.add(region.getRegionCode());
                values.add(dicRegions.get(0).getRegionCode());
            }

            map.put("values",values);
        }else {
            values.add(region.getSeniorRegionCode().substring(0,2));
            values.add(region.getSeniorRegionCode());
            values.add(region.getRegionCode());
            map.put("values",values);
        }
        List<SelectItem> selectItems = new ArrayList<>();
        List<SelectItem> items = new ArrayList<>();//下一级
        List<SelectItem> list = dicRegionMapper.selectAllAddress();
        for (SelectItem selectItem : list) {
            if (selectItem.getValue().equals(region.getRegionCode()) && region.getRegionLevel() != 4) {
                selectItems.add(selectItem);
            }
            if (region.getRegionLevel() == 3){
                 if (selectItem.getSeniorId().equals(region.getRegionCode())){
                     selectItem.setLeaf(true);
                    items.add(selectItem);
                }
            }else if(region.getRegionLevel() == 4){
                if (selectItem.getValue().equals(region.getRegionCode())) {
                    selectItem.setLeaf(true);
                    items.add(selectItem);
                }
            }
            if (selectItem.getValue().equals(region.getSeniorRegionCode())){
                if (!selectItem.getSeniorId().equals("0")){
                    Example example1 = new Example(DicRegion.class);
                    Example.Criteria criteria1 = example1.createCriteria();
                    criteria1.andEqualTo("regionCode", selectItem.getSeniorId());
                    DicRegion dicRegions = dicRegionMapper.selectByExample(example1).get(0);
                    SelectItem item = new SelectItem();
                    item.setValue(dicRegions.getRegionCode());
                    item.setLevel(dicRegions.getRegionLevel());
                    item.setLabel(dicRegions.getRegionName());
                    item.setSeniorId(dicRegions.getSeniorRegionCode());
                    selectItems.add(item);
                }
                selectItems.add(selectItem);

            }
        }
        list.clear();
        list = traversalAddress(selectItems, items, 3);
        List<SelectItem> item = new ArrayList<>();
        for(SelectItem selectItem : list) {
            if (selectItem.getValue().equals("45")) {
                item.add(selectItem);
            }
        }
        map.put("address",item);
        return  map;
    }

}
